0

I am currently developing a web application. I need to insert checkbox values into one table column names as breakfast. When I run the code data are inserted fine. but it display error message on the page as, Undefined index: breakfast and implode(): Invalid arguments passed. Here is my php code;

'<?php

$checkBox = implode(",", $_POST['breakfast']);

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

$query1="INSERT INTO dietplans (breakfast) VALUES ('" . $checkBox . "') ";     

mysqli_query($db,$query1);

}

?>'

Here is the HTML code;

        <h4><b>Breakfast(8.a.m.)</b></h4>
        <div class="form-check">
         
          <input type="checkbox" value="Full-fat milk  1 cup" name="breakfast[]">
          <label>Full-fat milk  1 cup</label>
        </div>
         <div class="form-check">
          <input type="checkbox" value="2 thin slices of bread with margerine " name="breakfast[]">
          <label>2 thin slices of bread with margerine </label>
        </div>
         <div class="form-check">
        
          <input type="checkbox" value="2 medium size bananas " name="breakfast[]">
          <label>2 medium size bananas</label>
        </div>
         
         
        <button type="submit" name="add" class="btn btn-dark ">Add my breakfast</button
Kevin
  • 19
  • 4

1 Answers1

-1

These are arrays you need define their indexes

for($i=0; $i<count($_POST['breakfast']); $i++){
   $query1="INSERT INTO dietplans (breakfast) VALUES ('" . 
    $_POST['breakfast'][$i] . "') ";     
    mysqli_query($db,$query1);
  }

This will iterate over all the submitted fields and insert for each index starting from 0

Ezekiel Arin
  • 115
  • 6
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Dec 25 '20 at 23:05