www.webdeveloper.com
Results 1 to 4 of 4

Thread: insert input textx as array into database

  1. #1
    Join Date
    Apr 2014
    Posts
    10

    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:
    from2.jpg

    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-Z\s]$/', $childfname))
    	{
    	$a = ucwords($childfname);
    	 if(preg_match('/^[a-zA-Z\s]$/', $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');
    		}
                  }
    	    }
              }
            }
          }
        }
      }
    }
    ?>
    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>
    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

  2. #2
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    663
    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.

  3. #3
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,251
    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.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  4. #4
    Join Date
    May 2014
    Posts
    843
    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 giant red warning boxes in the manual? At least then you could axe all those variables for nothing and endless crappy 'escape' functions -- since something like PDO::Prepare 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:

    Code:
    	<fieldset>
    
    		<legend><span>Child <span class="number"></span></legend>
    		<!--
    			SPAN is there as LEGEND are hard to style consistently cross-browser
    			but we want a LEGEND for semantics and accessibility...
    		-->
    		
    		<label for="child_Salutations">Salutation:</label>
    		<select name="formName[child][salutations]" id="child_Salutations">
    			<option value="" disabled selected>S</option>
    			<option value="Datin">Datin</option>
    			<option value="Datin Paduka">Datin Paduka</option>
    		</select>
    		<br />
    		
    		<label for="child_FirstName">First Name:</label>
    		<input type="text" name="formName[child][:firstName]" id="child_FirstName" />
    		<br />
    		
    		<label for="child_LastName">Last Name:</label>
    		<input type="text" name="formName[child][:lastName]" id="child_LastName" />
    		<br />
    		
    		<label for="child_DoB">Date of Birth:</label>
    		<input type="text" name="formName[child][:dob]" id="child_DoB" />
    		<br />
    		
    		<label for="child_Address1">Home Address (line 1):</label>
    		<input type="text" name="formName[child][:address1]" id="child_Address1" />
    		<br />
    		
    		<label for="child_Address2">(line 2):</label>
    		<input type="text" name="formName[child][:address2]" id="child_Address2" />
    		<br />
    		
    		<label for="child_MobileNum">Mobile Number:</label>
    		<input type="text" name="formName[child][:mobile]" id="child_MobileNum" />
    		<br />
    		
    		<label for="child_OfficeNum">Office Number:</label>
    		<input type="text" name="formName[child][:mobile]" id="child_OfficeNum" />
    		<br />
    		
    		<label for="child_eMail">E-Mail Address:</label>
    		<input type="email" name="formName[child][:email]" />
    		
    	</fieldset>
    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 fieldName identical to it's database counterpart, all you'd need to do for the SQL query is:

    Code:
    /* assumes $db is a connected PDO object */
    $statement = $db->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->execute($_POST['child']);
    ... and that's why I prefer PDO over mysqli (or the insecure mysql_ crap we were supposed to stop using the day PHP 5.1 dropped). 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.
    Last edited by deathshadow; 05-21-2014 at 05:13 PM.
    Java is to JavaScript as Ham is to Hamburger.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles