/    Sign up×
Community /Pin to ProfileBookmark

insert input textx as array into database

hi guys so i have this add contacts page and the form is divided into 3 different forms 1) primary contact 2)spouse and 3)child and the child form data is inserted as array into database because in the primary contact part of the form there is a “Children ?” with yes and no radio button and if yes a drop down list is enabled(1,2,3,4,5, etc…) where if user chooses say 2 then there would be 2 child form that appears and since there is 2 children then in the database a new row and data will be added accordingly.

image to be clearer:
[ATTACH]16145[/ATTACH]

i tried this:

[CODE]
<?php session_start();

if($_SESSION[‘sess_user_id’])
{
if(isset($_POST[‘submitC’]))
{
require “connection.php”;
$user = $_SESSION[‘sess_user_id’];
foreach($_POST[‘child-salutations’] as $index => $childsalutations)
{
$childsalutations = mysqli_real_escape_string($con, $index);
$childfname = mysqli_real_escape_string($con, $_POST[‘child-fname’][$index]);
$childlname = mysqli_real_escape_string($con, $_POST[‘child-lname’][$index]);
$cday = mysqli_real_escape_string($con, $_POST[‘cday’][$index]);
$cmonth = mysqli_real_escape_string($con, $_POST[‘cmonth’][$index]);
$cyear = mysqli_real_escape_string($con, $_POST[‘cyear’][$index]);
$chouse = mysqli_real_escape_string($con, $_POST[‘child-house’][$index]);
$cmobile = mysqli_real_escape_string($con, $_POST[‘child-mobile’][$index]);
$coffice = mysqli_real_escape_string($con, $_POST[‘child-office’][$index]);
$cemail = mysqli_real_escape_string($con, $_POST[‘child-email’][$index]);

if(preg_match(‘/^[a-zA-Zs]$/’, $childfname))
{
$a = ucwords($childfname);
if(preg_match(‘/^[a-zA-Zs]$/’, $childlname))
{
$b = ucwords($childlname);
if(preg_match(‘/^[+0-9-()s]*$/’, $cmobile))
{
if(preg_match(‘/^[+0-9-()s]*$/’, $coffice))
{
if(preg_macth(‘/^[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(.[a-zA-Z0-9-]+)*(.[a-zA-Z]{2,3})$/’, $cemail))
{
$add = “INSERT INTO child(chuser_id,child_id,c_name,c_dob,c_house,c_mobile,c_office,c_email) VALUES (‘$user’,”,’$childsalutations $childfname $childlname’,’$cday – $cmonth – $cyear ‘,’ $chouse ‘,’ $cmobile ‘,’ $coffice ‘,’ $cemail ‘)”;
$addchild = mysqli_query($con,$add) or die(mysqli_error());
if(!$addchild)
{
header(‘location : failed.php’);
}
else
{
header(‘location : event.php’);
}
}
}
}
}
}
}
}
}
?>
[/CODE]

but it doesn’t seem to be working like it doesnt read the code, as in when the submit button is clicked it just refreshes and no database inserted.

this is the child form just incase someone wanted to c. its a bit long, shortened where unnecessary:

[CODE]
<div style=”visibility:hidden”>
<table class=”prime”>
<tbody>
<br>
<tr><td style=”font-size:20px;font-weight:bold”>Child <span id=”number”></span></td></tr>
<tr>
<td>Salutation :</td>
<td><select name=”child-salutations[]” >
<option value=”” disabled selected>Salutations</option>
<option value=”Datin”>Datin</option>
<option value=”Datin Paduka”>Datin Paduka</option>
</select>
</td>
</tr>
<tr><td>First Name :</td><td><input type=”text” name=”child-fname[]” class=”style” /></td>
<td>Last Name :</td><td><input type=”text” name=”child-lname[]” class=”style” /></td></tr>
<tr>
<td>Date of Birth : </td>
<td>
<select name=”cday[]”>
<option value=””selected disabled>Day</option>
<option value=”1″>1</option>
<option value=”2″>2</option>
<option value=”3″>3</option>
<option value=”4″>4</option>
</select>
<select name=”cmonth[]”>
<option value=”” selected disabled>Month</option>
<option value=”1″>January</option>
<option value=”2″>February</option>
<option value=”3″>March</option>
<option value=”4″>April</option>
</select>
Year : <input type=”text” name=”cyear[]” maxlength=”4″ size=”4″ class=”year”>
</td>
</tr>
<tr><td>House Address</td></tr>
<tr><td>Line 1 :</td><td><input type=”text” name=”child-house[]” size=”20″ class=”style” /></td>
<td>Mobile No :</td><td><input type=”text” name=”child-mobile[]” class=”style” maxlength=”20″/></td></tr>
<tr><td>Office No :</td><td><input type=”text” name=”child-office[]” class=”style” /></td>
<td>Email Address : </td><td><input type=”email” name=”child-email[]” class=”style” /></td></tr>
</tbody>
</table>
</div>
[/CODE]

the table is in a hidden div because the table is cloned into the form when user chooses a number from the drop down list.

thanks in advance

[canned-message]attachments-removed-during-migration[/canned-message]

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@ginerjmMay 21.2014 — You asked this question on another forum and got the correct answer. Basically - you DON'T put 'arrays' into databases. You won't find another answer here.
Copy linkTweet thisAlerts:
@NogDogMay 21.2014 — You can put a PHP array into a database text field by serialize()-ing it, but it then becomes useless for any sort of DB search/sort activities.

A better solution in terms of scalability, robustness, etc. (IMHO) would be a database design change to put children in a separate table with a foreign key to the parent table.
Copy linkTweet thisAlerts:
@deathshadowMay 21.2014 — Well, your PHP is gibberish, and contrary to what others are saying you CAN put an array into a database, if you STOP writing your SQL like it's still 2004 with the deprecated mysql_ functions -- you know, hence the [url=http://us3.php.net/function.mysql-connect]giant red warning boxes[/url] in the manual? At least then you could axe all those variables for nothing and endless crappy 'escape' functions -- since something like PDO:?repare and PDOStatement::Execute can do exactly what you are asking, dump an array into a database.

You'd also have a lot better a time of it if you had semantic markup and a form structure that... well... made sense. I mean tables for layout, inlined style, no LABEL or semantic relationship between INPUT and LABEL, and since that display state is inlined, likely no graceful degradation scripting off either. Laundry list of how not to code a form.

Likewise if the value of your option is the same as it's content, you don't need to use value... and as a USER I'd just use a text input to let people type in the blasted date, but that's because select for 30+ days and chrismas knows how many years is ANNOYING AS HELL!

Your method of indexing those elements is just asking for it to fail. Never been a fan of [] and blinding hoping it works, but more so if you made your indexes be meaningful, you could just grab and insert each one the same way.

Of course, your database fields don't even correspond to the data you're shoving into the query -- see how you have fname and lname being put in, but the database only has c_name? Your database fields don't even make sense given your form! Much less the child ID -- shouldn't that be an auto-increment (probably the KEY) in the database and as such NOT even in the INSERT statement?

I'm guessing WILDLY here, but I'd approach that thus:

&lt;fieldset&gt;

<i> </i> &lt;legend&gt;&lt;span&gt;Child &lt;span class="number"&gt;&lt;/span&gt;&lt;/legend&gt;
<i> </i> &lt;!--
<i> </i> SPAN is there as LEGEND are hard to style consistently cross-browser
<i> </i> but we want a LEGEND for semantics and accessibility...
<i> </i> --&gt;

<i> </i> &lt;label for="child_Salutations"&gt;Salutation:&lt;/label&gt;
<i> </i> &lt;select name="formName[child][salutations]" id="child_Salutations"&gt;
<i> </i> &lt;option value="" disabled selected&gt;S&lt;/option&gt;
<i> </i> &lt;option value="Datin"&gt;Datin&lt;/option&gt;
<i> </i> &lt;option value="Datin Paduka"&gt;Datin Paduka&lt;/option&gt;
<i> </i> &lt;/select&gt;
<i> </i> &lt;br /&gt;

<i> </i> &lt;label for="child_FirstName"&gt;First Name:&lt;/label&gt;
<i> </i> &lt;input type="text" name="formName[child][:firstName]" id="child_FirstName" /&gt;
<i> </i> &lt;br /&gt;

<i> </i> &lt;label for="child_LastName"&gt;Last Name:&lt;/label&gt;
<i> </i> &lt;input type="text" name="formName[child][:lastName]" id="child_LastName" /&gt;
<i> </i> &lt;br /&gt;

<i> </i> &lt;label for="child_DoB"&gt;Date of Birth:&lt;/label&gt;
<i> </i> &lt;input type="text" name="formName[child][:dob]" id="child_DoB" /&gt;
<i> </i> &lt;br /&gt;

<i> </i> &lt;label for="child_Address1"&gt;Home Address (line 1):&lt;/label&gt;
<i> </i> &lt;input type="text" name="formName[child][:address1]" id="child_Address1" /&gt;
<i> </i> &lt;br /&gt;

<i> </i> &lt;label for="child_Address2"&gt;(line 2):&lt;/label&gt;
<i> </i> &lt;input type="text" name="formName[child][:address2]" id="child_Address2" /&gt;
<i> </i> &lt;br /&gt;

<i> </i> &lt;label for="child_MobileNum"&gt;Mobile Number:&lt;/label&gt;
<i> </i> &lt;input type="text" name="formName[child][:mobile]" id="child_MobileNum" /&gt;
<i> </i> &lt;br /&gt;

<i> </i> &lt;label for="child_OfficeNum"&gt;Office Number:&lt;/label&gt;
<i> </i> &lt;input type="text" name="formName[child][:mobile]" id="child_OfficeNum" /&gt;
<i> </i> &lt;br /&gt;

<i> </i> &lt;label for="child_eMail"&gt;E-Mail Address:&lt;/label&gt;
<i> </i> &lt;input type="email" name="formName[child][:email]" /&gt;

<i> </i>&lt;/fieldset&gt;


Should be ALL you need for the form. Set the label to display:inline-block, and an elastic (em) width, with text-align:right; -- trust me on that, no table needed. that's the SEMANTIC markup for building a form PROPERLY!

See how I did "formName[child][fieldName]" -- if you make the [i]fieldName[/i] identical to it's database counterpart, all you'd need to do for the SQL query is:

/* assumes $db is a connected PDO object */
$statement = $db-&gt;prepare('
INSERT INTO child (
userid, salutation, firstname, lastname, dob,
addr1, addr2, mobile, office, email
) values (
:userId, :firstName, :lastName, :dob,
:addr1, :addr2, :mobile, :office, :email
)
');

$_POST['child'][':userId'] = $user;

$statement-&gt;execute($_POST['child']);


... and that's why I prefer PDO over mysqli [i](or the insecure mysql_ crap we were supposed to stop using the day PHP 5.1 dropped)[/i]. Try that with bindParam. No "realEscapeString" sanitization nonsense needed, PDO handles that for you.

Naturally you'd want some element validation on that -- I'd probably have it work like how I do all my forms -- have the form built off a static array that includes the field type, so I could use that array to also verify the field values. Oh, and on rejection for errors, might be a good idea to re-issue the form since again, client side validation shouldn't be trusted.
×

Success!

Help @noobdvlpr spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...