Insert data in form element does not insert into my tables?

What i want to do here is to inser all my products into the table called cart . I used POST method in form action to post the data to my tables. But i am unsure why my data does not insert sucessfully into my cart tables. I make sure i named every variables properly but i do not know where did it goes wrong.can anyone please show me a helping hand? I really need help for this. Any form of help will be appreciated. Thanks!

<div class="col-12">
        <div class="card">
         
          <div class="card-body">
          <form action="includes/add-item-to-cart-invoice.php" method="post">

          <h4 class="card-title"> Step 2: Insert Selected Product Values</h4>
            <div class="table-responsive" style="max-height: 60vh">
        <div>
            <?php if(isset($message)) { echo $message; } ?></div>
            <!--<form method="post" action="">-->
              <table class="table">
                <thead class="text-primary">
                  <th style=" position: sticky;top: 0; background: white";>
                    Product
                  </th>
                  <th style=" position: sticky;top: 0; background: white";>
                    Name
                  </th> 
                  <th style=" position: sticky;top: 0; background: white";>
                    Avaliable Stock
                  </th> 
                  <th style=" position: sticky;top: 0; background: white";>
                    Item Price(RM)
                  </th>
                  <th style=" position: sticky;top: 0; background: white";>
                   Insert Product Quantity
                  </th>
                </thead>
                <tbody id="products">
                  <?php
                    $product_id = $_REQUEST['id'];
                    $ids = explode(",",$product_id);
                    $ids = array_splice($ids, 0);
                 
                    foreach($ids as $product_id){
                    $sql = "SELECT *, products.id as product_id FROM products 
                    LEFT JOIN sellers ON products.seller_id = sellers.id 
                    WHERE products.id = '".$product_id."' 
                    ORDER BY product_created DESC  ";
                    $query = $conn->query($sql);
                    {
                    while ($row = $query->fetch_assoc()) {
                        $max = $row['product_stock'];
                  ?>

                  <tr>
                   
                 
                    <td>
                      <?php echo $row['product_title']; ?>
                    </td>
                    <td>
                      <?php echo $row['product_stock']; ?> <?php echo $row['product_unit']; ?>
                    </td>
                    <td>
                    <div class="col-md-6">
                    <input type="number" name="cart_price" step=".01" class="form-control text-center" required>
                    </div>
                    </td>  
                    <td>
                    <div class="col-md-6">
                    <input type="number" name="cart_qty" step=".01" class="form-control text-center" required> 
                    </div>
                    </td>
                    </div>
                  <?php
                      }
                  }
                }
                  ?>
                </tbody>
              </table>
              
            </div>
          </div>
          <div class="card-body">
          <h4 class="card-title"> Step 3: Insert User ID</h4>
           <h6 class="card-title"><span class="text-danger">**Please make sure the User ID you enter exist**</span> </h6>
           <div class="form-group">
                    <label>SELECT SELLER *</label>
                    <select class="form-control" name="user_id" placeholder="search user..." required>
                    <!-- <option value="">Select a customer...</option> -->
                      <?php
                      $ssql = "SELECT * FROM users";
                      $squery = $conn->query($ssql);
                      while ($srow = $squery->fetch_assoc()) {
                      ?>
                      <option value="<?php echo $srow['id'];?>" ><?php echo $srow['user_fullname'];?></option>
                      <?php } ?>
                    </select>
                  </div>

            <div class="col-md-4">
          <!-- <input type="number" name="user_id" class="form-control text-center" required> -->
          <input type="hidden" name="cart_name" value="<?php echo $row['product_title']; ?>">
          <input type="hidden" name="cn_cart_name" value="<?php echo $row['product_title']; ?>">
          <input type="hidden" name="m_cart_name" value="<?php echo $row['product_title']; ?>">
          <input type="hidden" name="cart_image" value="<?php echo $row['product_photo']; ?>">
          <input type="hidden" name="cart_unit" value="<?php echo $row['product_unit']; ?>">
          <input type="hidden" name="product_id" value="<?php echo $row['id']; ?>">
          <input type="hidden" name="seller_id" value="<?php echo $row['seller_id']; ?>">
          </div>
            </div>
          </div>
                    
         <div class="d-flex p-4 justify-content-around">
                <div class="row">
            <button type="button" name="btn_delete" id="btn_previous" value="True" class="btn btn-danger btn-icon-split m-2" onclick="window.location='add-invoice.php'">
                        <span class="icon text-white-50">
                        </span>
          <i class="fa fa-arrow-left" aria-hidden="true"></i>
                        <span class="text">Back</span>
                    </button>
                <button type="submit" name="add_invoice_details" id="btn_next" value="True" class="btn btn-info btn-icon-split m-2">
                        <span class="icon text-white-50">
                        </span>
          <i class="fa fa-arrow-right" aria-hidden="true"></i>
                        <span class="text">Next</span>
                    </button>
                    </div>
            </div>
    </form>
   
          <!--</form>-->
        </div>
      </div>
    </div>
  </div>
</div>

This is my add-item-to-cart-invoice.php

<?php

include(’…/session.php’);

if(isset($_POST[‘add_invoice_details’])) {
$cart_name = $_POST[‘cart_name’];
$cn_cart_name = $_POST[‘cn_cart_name’];
$m_cart_name = $_POST[‘m_cart_name’];
$cart_image = $_POST[‘cart_image’];
$cart_qty = $_POST[‘cart_qty’];
$cart_unit = $_POST[‘cart_unit’];
$cart_price = $_POST[‘cart_price’];
$product_id = $_POST[‘product_id’];
$seller_id = $_POST[‘seller_id’];
$user_id = $_POST[‘user_id’];

// $sql = "SELECT * FROM cart WHERE product_id = '$product_id' AND user_id = '$user_id' ";
$query = $conn->query($sql);

if (!mysqli_num_rows($query)) {
  $sql = "INSERT INTO `cart` (`cart_name`,`cn_cart_name`,`m_cart_name`, `cart_image`, `cart_qty`, `cart_unit`, `cart_price`, `product_id`, `user_id`, `seller_id`) VALUES ('$cart_name','$cn_cart_name','$m_cart_name', '$cart_image', '$cart_qty','$cart_unit', '$cart_price', '$product_id', '$user_id', '$seller_id')";
} 
else {
  $row = $query->fetch_assoc();
  $cart_qty = $_POST['cart_qty'] + $row['cart_qty'];

  $sql = "UPDATE cart SET `cart_qty` = '$cart_qty' WHERE product_id = '$product_id' AND user_id = '$user_id' ";
}

if($conn->query($sql)) {
  //$_SESSION['success'] = 'Product added to Cart';
}
else {
  //$_SESSION['error'] = $conn->error;
}
header('Location: cart.php');

}
?>

My suggestion would to take one thing at a time. You should use separate HTML forms (one for creating and the other for updating) and keep the HTML separated as much as possible from the PHP code.

A Create example:

<form id="formData" class="form_classes" action="create.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="cms[user_id]" value="3">
    <input type="hidden" name="cms[author]" value="John Pepp">
    <input type="hidden" name="action" value="upload">
    <div class="file-style">
        <input id="file" class="file-input-style" type="file" name="image">
        <label for="file">Select file</label>
    </div>
    <select class="select-css" name="cms[page]">
        <option value="index">Home</option>
        <option value="blog" selected>Blog</option>
        <option value="about">About</option>
    </select>
    <div class="heading-style">
        <label class="heading_label_style" for="heading">Heading</label>
        <input class="enter_input_style" id="heading" type="text" name="cms[heading]" value="" tabindex="1" required
               autofocus>
    </div>
    <div class="content-style">
        <label class="text_label_style" for="content">Content</label>
        <textarea class="text_input_style" id="content" name="cms[content]" tabindex="2"></textarea>
    </div>
    <div class="submit-button">
        <button class="form-button" type="submit" name="submit" value="enter">submit</button>
    </div>

That way it will be easier to workout all the syntax errors and easier to read.

I would also learn PDO over mysqli as it is more versatile and a little more future proof in my opinion. A good resource can be found here - https://phpdelusions.net/pdo

I will show how I would go about coding the create (insert) PHP code to insert data, but you should really get a tutorial or figure it out on your own as it will sink in better.

/*
 * Insert New Data doing it the procedural way
 */
function create(array $data, $pdo) {
    try {
        /* Initialize an array */
        $attribute_pairs = [];

        /*
         * Set up the query using prepared states with the values of the array matching
         * the corresponding keys in the array
         * and the array keys being the prepared named placeholders.
         */
        $sql = 'INSERT INTO cart (' . implode(", ", array_keys($data)) . ')';
        $sql .= ' VALUES ( :' . implode(', :', array_keys($data)) . ')';

        /*
         * Prepare the Database Table:
         */
        $stmt = $pdo->prepare($sql);

        /*
         * Grab the corresponding values in order to
         * insert them into the table when the script
         * is executed.
         */
        foreach ($data as $key => $value)
        {
            if($key === 'id') { continue; } // Don't include the id:
            $attribute_pairs[] = $value; // Assign it to an array:
        }

        return $stmt->execute($attribute_pairs); // Execute and send boolean true:

    } catch (PDOException $e) {

        /*
         * echo "unique index" . $e->errorInfo[1] . "<br>";
         *
         * An error has occurred if the error number is for something that
         * this code is designed to handle, i.e. a duplicate index, handle it
         * by telling the user what was wrong with the data they submitted
         * failure due to a specific error number that can be recovered
         * from by the visitor submitting a different value
         *
         * return false;
         *
         * else the error is for something else, either due to a
         * programming mistake or not validating input data properly,
         * that the visitor cannot do anything about or needs to know about
         *
         * throw $e;
         *
         * re-throw the exception and let the next higher exception
         * handler, php in this case, catch and handle it
         */

        if ($e->errorInfo[1] === 1062) {
            return false;
        }

        throw $e;
    } catch (Exception $e) {
        echo 'Caught exception: ', $e->getMessage(), "\n"; // Not for a production server:
    }

    return true; // probably should be false if everything fails. 
}

$result = create($_POST['product'], $pdo); // $pdo is the connection string

Where $_POST[‘product’] is an array of ALL the data and just look at the HTML form to see what I am talking about. Though like I said I would find something more basic where it will make more sense to you. Another thing is COMMENT your code that way it will help learn it better and 6 months when you look at the code it will be better to decipher, plus it help other coders that look at your code as well.

HTH John

Sponsor our Newsletter | Privacy Policy | Terms of Service