0

I have a HTML form that retrieves a varying number product types that the user inputs stock figures. This data then needs to be INSERTED to a new table. Here is the PHP query that populates the form.

require_once 'config.php';

$i = 1;

$sql = "SELECT * FROM dealer_product WHERE customer_code='$custcode' ORDER BY prod_code";
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result)) {

$prodcode = $row['prod_code'];

echo "<tr><td><input type='text' name='prod".($i++)."' value='" . $prodcode . "'/></td><td><input type='number' name='openstock".($i++)."'/></td><td><input type='number' name='sold".($i++)."'/></td></tr>";

}

mysql_close($con);
?>

I know how to INSERT a set number of multiple records, but how do I INSERT a varying number of records? Thanks in advance. Sorry for my basic knowledge, I'm a network admin not PHP MYSQL.

  • Because it will be posted... http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – ApplePie Nov 28 '13 at 00:33
  • You should use an HTML array instead of appending `$i` to the end of each input, then you can loop easily through the array in PHP. – scrowler Nov 28 '13 at 00:34

2 Answers2

0

Name your input fields as if they were arrays, e.g.:

<input name="prods[0]" />

You can then output a variable number of inputs in your HTML, even add more with JavaScript. PHP will convert the input to an array over which you can iterate:

<?php
    foreach ($_POST['prods'] as $prod) {
        /* Process $prod */
    }
?>
Tom H
  • 85
  • 1
  • 8
0

I recommend that you go in the same way but using

while ($row = mysql_fetch_assoc($result))

And now you have not numbers as index that is more complicated way to see things, better see associative way that's the column name from your table in mysql.

And you're doing a lot of increments there doing $i++ a lot of times. I don't know if you're doing that intentionally but if not just increment $i once.

Also the number of row can be reached using this:

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

Look inside the manual

http://us1.php.net/mysql_fetch_assoc

mario ruiz
  • 880
  • 1
  • 11
  • 28