View Full Version : Problem inserting multiple records into database

09-12-2011, 06:26 PM
I have a query that is displaying potential items to add to a final invoice. The query returns multiple rows and I need to be able to allow the user to click a "complete" button and finalize this invoice. A couple of things that need to happen:

1) the user should have to click a checkbox next to each record and only those records that are checked would be included
2) each records should be stored in a new table (e.g. CompleteInvoice)

What I have below is only inserting 1 record (and there should be 12 in this particular case) and when I do an echo var_dump($_POST) there is also just the one record's info being displayed. I need to insert all the records, any ideas (the checkbox issue can come after, I think I need to figure out the multiple insert problem first).

<form method="post">

while ... {
<input type="hidden" name="CompleteValue[CompleteTimeId]" value="<?php echo $Row['TimeId'];?>" />
<input type="hidden" name="CompleteValue[CompleteTimeUser]" value="<?php echo $Row['TimeUser'];?>" />
} // end while


The INSERT ...

if (isset($_POST['Insert'])) {

$random = substr(number_format(time() * rand(),0,'',''),0,6);

$sql = "";
foreach($_POST['CompleteValue'] as $key => $val){
if($val != ""){
$sql .= "'$val',";

$sql = substr($sql,0,-1);

$insertSQL = "INSERT INTO `TimeCompleteInvoice` (InvoiceID,CompleteTimeId,CompleteTimeUser) VALUES ('$random',$sql)";

header("Location: mysite.com...");

09-12-2011, 07:38 PM
The main issue here, is that you're setting the columns you want to update without checking if there's a value to go into them. For example, your query will look like this if CompleteTimeID is blank -
INSERT INTO `TimeCompleteInvoice` (InvoiceID,CompleteTimeId,CompleteTimeUser) VALUES ('$random','CompleteTimeUser)"; - which will produce an error in your mysql.

Best course of action would be to change your query to this:

mysql_query($insertSQL) or die(mysql_error());

And work on the errors from there :). You will need to specify a columns string, as well as the values string, in the foreach statement you have. Then, change your mysql to use the columns string for the columns :)

09-12-2011, 08:23 PM
Think I might have misread your post...Are you wanting checkboxes for rows in mysql? If so, then you should just have input type="checkbox" being filled out with your required properties. Probably better to pass the name as checkboxes[] and the values as row id's so that you can refer to the mysql rows by the unique identifier, then just populate your completeinvoice table with these values.

09-13-2011, 08:26 AM
hi just go through the link gotocode.com/art.asp?art_id=289&