I have 4 rows that need to be inserted into db IF THEY ARE NOT EMPTY. But I can't make it work.
this x 4 times
<select class="form-control" id="masura" name="masura[]">
<option value='' > -- </option>
<option value='XS' > XS </option>
</select>
<input type="text" class="form-control" id="stoc" name="stoc[]" >
and this php
$row_data = array();
foreach($_POST['stoc'] as $row=>$stoc) {
$stoc=mysqli_real_escape_string($link,$stoc);
$masura=mysqli_real_escape_string($link,($_POST['masura'][$row]));
$row_data[] = "('$masura', '$stoc' , '$dirName')";
}
if (!empty($row_data)) {
$sql = 'INSERT INTO stoc (masura, stoc, prodid) VALUES '.implode
(',', $row_data);
$result = mysqli_query($link, $sql);
}
the issue is that it will also insert empty fields (if I enter only 1 field, it will insert that field with other 3 ones empty)
Thanks
Don't add empty fields to $row_data
:
foreach($_POST['stoc'] as $row=>$stoc) {
if (empty($stoc) || empty($_POST['masura'][$row])) {
// Skip if either field is empty
continue;
}
$stoc=mysqli_real_escape_string($link,$stoc);
$masura=mysqli_real_escape_string($link,($_POST['masura'][$row]));
$row_data[] = "('$masura', '$stoc' , '$dirName')";
}