Jump to content

Recommended Posts

Can anyone tell me what's making  this code put an extra entry in the database?Whatever the number of looped students being added, it adds another row with nothing but the registrationid entered.

 

<?php
// connect to database 
include("databaseconn.php"); 			

// store all posted intemnos and descriptions in local arrays 
$fname = $_POST['fname']; 
$lname = $_POST['lname']; 
$phone = $_POST['phone']; 
$email = $_POST['email']; 
$bdate = $_POST['bdate'];
$bdate2 = $_POST['bdate2'];
$bdate3 = $_POST['bdate3'];
$wid = $_POST['wid']; 
$rid = $_POST['reg_id'];
$reg_alone = $_POST['reg_alone'];

$_SESSION['workshops']=$wid;
?>


<?

if(sizeof($_POST['fname'])) {
// loop through array 
$number = count($fname); 
for ($i=0; $i<=$number; $i++) 
{ 
    // store a single item number and description in local variables 
    $fnames = $fname[$i]; 
    $lnames = $lname[$i];
    $phones = $phone[$i]; 
    $emails = $email[$i];
    $bdates = $bdate[$i];
    $bdates2 = $bdate2[$i];
    $bdates3 = $bdate3[$i];
    $wids = $wid[$i];
    $rids = $rid[$i];	
echo "echod ".$bdates2."and<br>";
print_r($bdates2);
		$query_insertItemWorkshop = "INSERT INTO tbl_attendees (attendee_fname, attendee_lname, attendee_registrationid, workshop_id, attendee_email, attendee_telephone, attendee_bday, attendee_bmonth, attendee_byear) VALUES ('$fnames', '$lnames', '$reg_alone', '$wids', '$emails', '$phones', '$bdates', '$bdates2', '$bdates3')";

		echo "query: ".$query_insertItemWorkshop;
		$dberror = "";
		$ret = mysql_query($query_insertItemWorkshop);




}
}
    ?>

Link to comment
https://forums.phpfreaks.com/topic/258677-loop-adds-an-extra-entry-to-db/
Share on other sites

Your counting $fname which should theoretically come to 1 so your saying for(i = 0; i <= 1; i++) which will cycle through twice; once for 0 and once for 1.

 

If your just trying to add your $_POST data to the database all you need to do is remove the for loop and execute your query. using $fname, $lname etc. There's no need what so ever to have the for loop in there.

This code makes little to no sense.

Why are you treating $_POST values as arrays by using count and sizeof, when they should be strings.

Why are you using a loop at all? unless you have multiple <inputs>s will array names.

But if you are only expecting one row to be inserted, I'd say that's not the case.

Do you have several fields with the same name? That doesn't work. Each field is unique and needs its own name that will then be posted.

 

Hence, you should neither loop on POST variables. They are atomic strings.

 

Also, you don't escape the strings in the SQL query. Never user the "$variable" syntax for that reason. What if some text contains apostroph? Never assume that strings are escaped beforehand (deprecated from PHP).

 

Sorry, but you need to read documentation on how PHP and SQL work.

 

Cheers

To answer your questions, it isn't actually my code. I've taken over somebody else's unfinished project. On previous pages the user selects several classes and how many students they're putting in each. Then on this page it generates a loop of fields for each class to enter info for each student. They hit submit and it adds the students to the table. So, yes that's multiple inputs, if I'm understanding right?

 

I'm at a lower php level, and struggle to understand how to work with arrays and loops, so I'm not sure what's going on. I can answer any questions to the best of my ability.

 

edit: or maybe I should not say lower level? if this isn't even written well :)

Do you have several fields with the same name? That doesn't work. Each field is unique and needs its own name that will then be posted.

 

Hence, you should neither loop on POST variables. They are atomic strings.

 

Neither of these statements are true.

you can have input names in array format, though it's typically avoided.

Just tried that change. Still put in the empty extra row. hmmm

 

Any thoughts on how I can go about this? I was hoping not to have to rewrite the code, but if there's an easy way to go about it.

 

Sucks trying to figure out somebody else's work.

 

If it helps any, I can show you the mess on the previous page that generates the data posted to the page above.

 

  <? 
/*code above this for credit card transaction, and depositing session data in the table. I added that because he had it originally going into the tables on each successive page, and people were backtracking and putting in duplicate entries. grrr.
  
//$query_selectAllItems = "SELECT *, DATE_FORMAT(workshop_date, '%e-%m-%Y') as 'my_date' FROM tbl_workshops"; 
$query_selectAllItems = "SELECT * FROM tbl_registration_workshop, tbl_workshops where tbl_registration_workshop.registration_id=$reg_id and tbl_registration_workshop.workshop_id !='0' and tbl_registration_workshop.workshop_id = tbl_workshops.workshop_id"; 
@$result_all = mysql_query($query_selectAllItems);
@$numRows_all = mysql_num_rows($result_all);

//output each row 
  while ($c_row = mysql_fetch_array($result_all)){
  
  
  ?>
      <tr><td colspan="9"><b><?= $c_row['workshop_title'] ?></b></td></tr>
      <tr><td colspan="9"><br /><br /></td></tr>

  $count = $c_row['regworkshop_qty'];
  
  $i = 1;
while ($i <= $count) {
     $i++;  /* the printed value would be
                   $i before the increment
                   (post-increment) */
			   $x = $i-1
			   
			   
?><tr><td colspan=4><b><?= $reg_id ?> Enrollee #<?= $x ?></b><img src="/images/greenblack.gif" style="height:2px; width:450px;position:relative;left:5px;top:-3px;"></td></tr>
    <tr><td align=right style="padding-right:4px;">First Name</td><td style="padding-right:10px;"><input type="text" name="fname[]" id="fname" onfocus="this.className='reg_live';" onblur="this.className='reg_off';" /></td>  <td align=right style="padding-right:4px;">Last Name</td><td><input type="text" name="lname[]" id="lname" onfocus="this.className='reg_live';" onblur="this.className='reg_off';"  /></td></tr>
    <tr><td align=right style="padding-right:4px;">Email</td><td style="padding-right:10px;"><input type="text" name="email[]"  onfocus="this.className='reg_live';" onblur="this.className='reg_off';" /></td>  <td align=right style="padding-right:4px;">Phone</td>  <td style="padding-right:10px;"><input type="text" name="phone[]"  onfocus="this.className='reg_live';" onblur="this.className='reg_off';" /></td> </tr>
    <tr><td align=right style="padding-right:4px;">Birthdate</td>  <td colspan=3>
    <select id="birth_month" name="bdate2[]" onfocus="this.className='reg_live';" onblur="this.className='reg_off';" >
<option value="">month</option>
  <option value="01">Jan</option>
  <option value="02">Feb</option>
  <option value="03">Mar</option>
  <option value="04">Apr</option>
  <option value="05">May</option>
  <option value="06">Jun</option>
  <option value="07">Jul</option>
  <option value="08">Aug</option>
  <option value="09">Sept</option>
  <option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
    
    
        <select id="birthday" name="bdate[]" onfocus="this.className='reg_live';" onblur="this.className='reg_off';" >
<option value="">day</option>
  <option value="01">01</option>
  <option value="02">02</option>
  <option value="03">03</option>
  <option value="04">04</option>
  <option value="05">05</option>
  <option value="06">06</option>
  <option value="07">07</option>
  <option value="08">08</option>
  <option value="09">09</option>
  <option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>

<select id="birthyear" name="bdate3[]" onfocus="this.className='reg_live';" onblur="this.className='reg_off';" >
<option value="">year</option>
  <option value="1993">1993</option>
  <option value="1994">1994</option>
  <option value="1995">1995</option>
  <option value="1996">1996</option>
  <option value="1997">1997</option>
  <option value="1998">1998</option>
  <option value="1999">1999</option>
  <option value="2000">2000</option>
  <option value="2001">2001</option>
  <option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<!--<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2018">2019</option>
<option value="2018">2020</option>-->
</select>
    
    <input type="hidden" value="<?= $c_row['workshop_id'] ?>" name="wid[]" /><input type="hidden" name="reg_id" value="<?= $reg_id ?>"  onfocus="this.className='reg_live';" onblur="this.className='reg_off';" /></td>  </tr><tr><td colspan="4"><br /><br /></td></tr>
    
    <?
}
  
  
  
  
    ?>



<tr><td colspan="4"><br /><hr style="color: #000;background-color: #000;height: 5px;"><br /></td></tr>
            

            
            
            
            
   <?
  } //end while
  ?>       
            
            <tr><td colspan="4"><input type="hidden" name="reg_id" value="<?= $reg_id ?>" /><input type="hidden" name="reg_id" value="<?= $reg_id ?>" />
    <input type="hidden" name="reg_alone" value="<?= $reg_alone ?>" />
    <input type="submit" value="Register" /></form></td></tr>
          </table>  

 

 

Turpentyne, the way your going about it is, without trying to sound too harsh, outright wrong.

 

As already mentioned you don't need to loop through anything to execute a query from $_POST data.

 

Lets use a simple example of how to process post data without taking into consideration any security measures for the purposes of helping you understand.

 

<form method="post">
    <input type="text" name="firstName" />
    <input type="text" name="lastName" />
    <input type="submit" name="subForm" value="Submit" />
</form>

 

The above form is executed which will refresh the page with the POST data in the header.

 

<?php

// Has the form been submitted?
if(isset($_POST['subForm'])){
    // Extract the $_POST data into its own variables. Creating the $firstName and $lastName variables.
    extract($_POST);

    // Construct the query and execute.
    $sqlString = "INSERT INTO `tblName` (`first_name`, `last_name`) VALUES ('".$firstName."', '".$lastName."')";
    $query = mysql_query($sqlString);
}

?>

 

The above code could be placed at the start of your PHP page which tests for the form submission and then processes the form before any html is output to the header.

 

Hope that helps a little.

Reading up on extract, it sounds like it's an insecure way? I can still just create the variables. but on the previous page, it's looping through form fields that would have the same name. Now that's  sounding like a potential problem?

 

Basically its:

 

Class 123: student 1's fname, lname,bday, etc.

                  student 2's fname,lname,bday, etc.

 

Class 456" student 3's fname,lname,bday, etc.

 

The way it's written, I believe this means there are three bits of info for fname, lname, bday and so on. Maybe this is why he was creating an array? Forgive my ignorance. I've never had to work with anything more than a simple form query insert. I tried what you explained above, and it only enters the first student. the other two are never entered. I assume... the reason for the loop?

 

 

 

 

As I suspected, the names are in array format.

Which means if you make the change that PFM suggested, it will add the correct amount of rows.

If it doesn't, something else is wrong and you should post the updated relevant code.

 

Gah!!! I appologize immensely! I think I had a gremlin issue going on here. PMF's suggestion seemed perfect. It was the first thing I tried. When it didn't work, I went (and led everyone else) on a wild goose chase. I knew something wasn't right with the direction we were going, but I'm not experienced enough to be sure.

 

I went back to a file version with PMF's suggestion, and it worked perfectly. I don't know if there was an issue with uploading the file or what. but it did actually solve the problem.

 

Sorry if I was overly nebulous on explaining that it was indeed arrays I was dealing with. I got side tracked looking into other solutions, when CPD took it back to a basic POST query insert.

 

Sorry 'bout that. problem solved.

 

Well, there are a few misleading and incorrect posts in this thread.

My first reply was to make sure that you were using array names in the inputs.

If they were not in array format then the code you posted would have been flat out incorrect.

Since they are in array format, only your loop needed changing, as PFM and myself suspected.

You can either change <= to <, or set i = 1;

When looping arrays, I myself like to set the index to 0 as you have done.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.