I have a form in which user can add more fields, as he want…
he can add 1,2,3,…. rows of fields..
the code that I use is here,
<?php
echo '
<form method="post" action="">
<input type="hidden" name="mod" value="'.$mod.'" />
<table style="width: 700px">
<tr>
<th>Description</th>
<th>Quantity</th>
<th>Price</th>
</tr>';
// Loop to prepare the display of 100 product lines
for ($i=0; $i<100; $i++) {
if ($text['quantity'][$i] == "") $text['quantity'][$i] = 1;
if ($text['unit'][$i] == "") $text['unit'][$i] = "0.00";
// Display only the first line
if ($nbr_ligne == 0) $nbr_ligne = 1;
if ($i >= $nbr_ligne) $display = 'style="display:none"';
echo '
<tr id="cell'.$i.'" '.$display.'>
<td>
<textarea name="text[detail]['.$i.']">'.stripslashes($text['detail'][$i]).'</textarea>
<br />
<a href="javascript:void(0)" onclick="javascript:document.getElementById(\'cell'.($i+1).'\').style.display=\'table-row\'; this.style.display=\'none\'">[+]</a>
</td>
<td>
<input name="text[quantity]['.$i.']" id="q'.$i.'" value="" size="4" />
</td>
<td>
<input name="text[unit]['.$i.']" id="u'.$i.'" value="" size="7" /> USD
</td>
</tr>';
}
echo '
</table>
<input type="submit" name="save" value="Save" />
</form>
';
?>
the fields are adding successfully.
now I want to store the values of these fields in database.
the code I use for this is:
if(isset($_POST['save']))
{
echo mysql_error($db);
extract($_POST);
$insert=mysql_query(" insert into add (description, quantity, price) values ('{$text['detail'][$i]}','{$text['quantity'][$i]}','{$text['unit'][$i]}')") or die("unable to insert");
}
but it does not work. plz help me guys. I need it very much.
The issue here is that $i has not been initialized in the script that you are using to save to the database. You will need to loop through from 0 to 100 and BREAK if a number does not exist. You’re also using the reserved keyword add. Use backticks ` on reserved keywords.
Not too fond of the way you’re looping on inserts, but the above piece of code should work, even though it’s clearly not the best solution. A better way would be to create one singular INSERT query that inserts multiple rows:
If you must loop on separate queries, you should use prepared statements for performance reasons.
Other issues: