lundi 26 décembre 2022

Saving array data in table rows to mysql database using checkbox

I have an order table in my project. I am pulling the products from the database to this table using foreach. I show the quantity and unit price calculation information on the table instantly with jquery. I want to save the data in this table from the row selected with the checkbox to the database. I tried a few things with foreach but it looped so it created a new record for each row in the database. I want to print arrays with implode using commas between them. For example, the data in the rows entered in the quantity field in the table should be entered in the quantity field in the database as 1,2,3,4. If I have to explain briefly, I want to make an insert in one go.

Table:Table Image

Table & Form Code:

<form action="" method="POST">
<table class="table table-sm mb-3 text-center align-middle">
   <thead>
      <tr>
         <th>Choose</th>
         <th>Product Name</th>
         <th width="137px">Quantity</th>
         <th>Unit Price</th>
         <th>Total Price</th>
      </tr>
   </thead>
   <tbody>
      <?php foreach($ProductTbl as $product){ ?>
      <tr>
         <th scope="row">
            <div class="form-check form-check-success"><input class="form-check-input" name="check[]" type="checkbox" value="<?= $product-> productid"></div>
         </th>
         <td><?= $product->productname ?></td>
         <td><input class="w-25 text-center quantity" type="text" name="quantity[]" value="0"></td>
         <td><input class="w-25 text-center unitprice" type="text" name="unitprice[]" value="<?= $product->unitprice ?>" disabled="disabled"> €</td>
         <td><input class="w-25 text-center totalprice" type="text"  name="totalprice[]" value="" disabled="disabled"> €</td>
      </tr>
      <?php } ?>
   </tbody>
</table>

<div class="text-center">
   <button class="btn btn-success col-md-2" type="submit" name="add">Offer Preview</button>
   <button class="btn btn-warning col-md-1" type="reset">Reset</button>
   <a href="#"><button class="btn btn-danger col-md-1" type="button">Cancel</button></a>
</div>

</form>


//The code structure I tried

   if(isset($_POST['add'])){
        $check         = $_POST['check']; 
        $quantity      = implode(',', $_POST['quantity']);
        $totalprice    = implode(',', $_POST['totalprice']);

        if (!empty($check)) { 
            foreach ($check as $chk => $value){

                // I printed it for testing.
                echo $value.' - product id in the checked checkbox<br>';
                print_r($quantity);
                print_r($totalprice);
            }
    }
}

How does this code work the way I want?




Aucun commentaire:

Enregistrer un commentaire