When i send post from php to save input values in seperate rows i’m ending with that in ma table always is stored extra blank rows. For example this is the form from which i send post to save values:
<table class="table table-bordered" id="data"> <tr> <th width="40%">Knjiga</th> <th width="40%">Pisac</th> <th width="5%">Radnja</th> </tr> <?php if(isset($_COOKIE["spisak_knjiga"])) { $cookie_data = stripslashes($_COOKIE['spisak_knjiga']); $knjiga_podaci = json_decode($cookie_data, true); foreach($knjiga_podaci as $keys => $values) { $skola= $values["skola"]; $inv_id= $values["inv_id"]; $sql = "SELECT knjige.id_knjige, knjige.naziv_knjige, knjige.pisac, knjige.mjesto_izdanja, knjige.godina_izdanja, knjige.signatura, knjige.inv_broj,knjige.kategorija, knjige_kategorija.naziv_kategorije, skole.ime_skole FROM knjige INNER JOIN skole ON knjige.skola = skole.id_skole INNER JOIN knjige_kategorija ON knjige.kategorija = knjige_kategorija.id_kat WHERE id_skole ='$skola' AND inv_broj = '$inv_id'"; mysqli_query($db, $sql); foreach ($db->query($sql) as $row){ $idKnjige = $row['id_knjige']; ?> <tr> <td><?php echo $row['naziv_knjige'] ?></td> <td><?php echo $row['pisac'] ?></td> </tr> <tr> <input type="hidden" name="ucenik[]" value="<?php echo $idUcenika; ?>"> <input type="hidden" name="knjiga[]" value="<?php echo $idKnjige; ?>"> <input type="hidden" name="skola[]" value="<?php echo $skola; ?>"> </tr> <?php } } $broj = mysqli_num_rows(mysqli_query($db, $sql)); $db->close(); ?> <?php } } ?> </table> <input type="submit" name="zaduziUcenika" class="btn btn-primary btn-lg btn-block" value="Save orders"> </form>
And this is where i receive data and insert into db, it insert all products that was in order but it also save extra empty rows.
if (isset($_POST['zaduziUcenika'])) { $i = 0; foreach ($_POST as $val) { $idUcenika = $_POST['ucenik'][$i]; $idKnjige = $_POST['knjiga'][$i]; $idSkole = $_POST["skola"][$i]; $sql = "INSERT INTO izdane_knjige (knjiga, ucenik, skola, datum_podizanja, stanje) VALUES ('$idKnjige', '$idUcenika', '$idSkole', CURRENT_DATE(), 0)"; $u = mysqli_query($db, $sql); $i++; } if($u) { header("Location: izdaj2.php?action=spremljeno&id=$idUcenika"); exit(); } }
Advertisement
Answer
Because there are other values in your $_POST
array than the ones you want to insert into your table, you are iterating too many times through your foreach
loop. Change the loop to iterate over one of the values you have multiple copies of instead e.g. ucenik
:
foreach ($_POST['ucenik'] as $i => $val) { $idUcenika = $_POST['ucenik'][$i]; $idKnjige = $_POST['knjiga'][$i]; $idSkole = $_POST["skola"][$i];
Note you will need to remove the $i = 0;
and $i++;
lines from your code.