Reputation: 1
I need a little help. I have the following code. I wish that when all fields are not completed, not to introduce the empty fields in the database. Just upload the completed them.
for($i = 0; $i <count($_POST)+3; $i++){
mysql_query("INSERT INTO `predare`(`id_factura`,`id_student`, `id_produs`, `cantitate`)
VALUES('".$_POST['id_factura'][$i]."','".$_POST['id_student'][$i]."', '".$_POST['id_produs'][$i]."', '".$_POST['cantitate'][$i]."');");
}
<input class="input-1" name="cantitate[]" id="cantitate" value="">
<input class="input-1" name="id_factura[]" id="id_factura" value="">
<input class="input-1" name="id_student[]" id="id_student" value="">
<input class="input-1" name="id_produs[]" id="id_produs" value="">
Upvotes: 0
Views: 230
Reputation: 41820
Here's how I would suggest doing it. First initialize your SQL string and a separator (for inserting multiple records with one query.)
$sql = "INSERT INTO `predare` (`id_factura`,`id_student`, `id_produs`, `cantitate`) VALUES ";
$separator = '';
Then loop over the submitted rows and append to the SQL string if the rows have all four values.
for ($i = 0; $i < count($_POST['cantitate']); $i++) {
$values = array();
foreach (array('id_factura', 'id_student', 'id_produs', 'cantitate') as $column) {
// only add values to the $values array if something has been entered
// (empty fields will be present as '', which evaluates to false)
if ($_POST[$column][$i]) $values[] = $_POST[$column][$i];
}
if (count($values) == 4) { // only add the values to the SQL if all fields are present
$sql .= "$separator ('" . implode("','", $values) . "')";
$separator = ',';
}
}
Then you can execute the SQL statement to insert all the complete records at once.
If you wanted to include incomplete (but not empty) rows, you could use
if ($values) {...
instead of if (count($values) == 4) {...
One benefit to setting it up this way is that it would be easier to convert the code to use a better database extension (such as PDO) with prepared statements instead of concatenating the values into the SQL like this.
Upvotes: 1
Reputation: 76
You need to go through the $_POST['id_factura'] array and You need to check the values before the insert statement like this:
for($i = 0; $i <count($_POST['id_factura']); $i++){
if(isset($_POST['id_factura'][$i]) && isset($_POST['id_student'][$i]) && isset($_POST['id_produs'][$i]) && isset($_POST['cantitate'][$i])){
mysql_query("INSERT INTO `predare`(`id_factura`,`id_student`, `id_produs`, `cantitate`)
VALUES('".$_POST['id_factura'][$i]."','".$_POST['id_student'][$i]."', '".$_POST['id_produs'][$i]."', '".$_POST['cantitate'][$i]."');");
}
}
Or you can check if the integer values are greater then 0...
Upvotes: 0