i want to insert into database several items with its quantity like name of food and its quantity using checkbox that handle the value of the food name.
here is the code:
<?php ........
if(mysqli_num_rows($res) > 0){
while($row = mysqli_fetch_array($res)){
echo "<tr>
<td><input type='checkbox' value='$row[0]' name='food[]'></td>
<td>
$row[0]
Qty: <input type='number' value='1' size='1' name='qty[]' id='qty'>
</td>
<td align=right>$row[3]</td>
</tr>";
}
}
?>
<input type='submit' value='Add checked' class='btn btnSearch' name='add' id='btnadd'>
</form>
action:
<?php
if(isset($_REQUEST['add']), $_REQUEST['food'])
{
$food = $_POST['food'];
$qty = $_POST['qty'];
$array = array_combine($food, $qty);
foreach($array as $f => $q){
$sql = "insert into entry (foodName,qty, meal_name, date, email) values ('$f', '$q' ,'$meal', '$date', '$email')";
mysqli_query($cn, $sql);
}
if(mysqli_affected_rows($cn) > 0)
header("location:fitness.php");
else
echo $sql;
}
?>
the problem is .. array $qty is taking all inputs of the table not just the checked.
and im getting the error:
Warning: array_combine(): Both parameters should have an equal number of elements in D:\ABC\First Stage\FitnessAddict\AddFood.php on line 93
To give you a better answer change this.
<td><input type='checkbox' value='$row[0]' name='food[]'></td>
to
<td><input type='hidden' value='$row[0]' name='food2[]'><input type='checkbox' value='$row[0]' name='food[]'></td>
then
in your code
foreach($_POST['food2'] as $key=>$val)
{
if (in_array($val,$food,true))
$array[$val] = $qty[$key];
}
That should work
So when you check a box in food, it compares the master list in food2 and says here's the matching key you can use for qty.
The issue is that the checkbox type only passes the checked values, and since you are using an array, you are losing the 'key' to reference qty.
This will give you an idea..to save
<?php
if(isset($_REQUEST['add']),$_REQUEST['food']) {
$food = $_POST['food'];
$qty = $_POST['qty'];
$foodcount = count($qty);
$i=0;]
foreach($qty as $quantity){
If(isset($food[$i]) && !empty($food[$i]))
{
$sql = "insert into entry (foodName,qty, meal_name, date, email) values ('$food[$i]', '$quantity' ,'$meal', '$date'
}
}
if(mysqli_affected_rows($cn) > 0){
header("location:fitness.php");
}else echo $sql;
} ?>