Sunny Sunny - 3 months ago 8
MySQL Question

logic for adding users in database

I am building an E-Commerce website and store products(id & quantity) in session["cart_array"](From Adam Khoury's Tutorials :P). Now I want that I can insert these product details to table known as costumer_orders. I need some logic that can extract these details from the table products and then insert these in customer_orders table. If there is another best solution then please suggest it.
This is my code

<?php
$dynamicDisplay = '';
if (isset($_SESSION["name"]) && !empty($_SESSION['name'])) {
$name = $_SESSION['name'];
//VARIABLES TO SHOW SELETED ITEMS BY THE USER
$dynamicDisplay .= '<h1>Thank <?php echo $name;?> for Ordering from Us.</h1>';
$dynamicDisplay .= 'Your Order Details are: <br/>';
$dynamicDisplay .= '<ol>';

//FOREACH LOOP FOR ACCESSING ALL ITEMS FROM THE CART
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item["item_id"];
$sql = mysqli_query($con, "SELECT * FROM products WHERE id='$item_id' LIMIT 1");
while ($row = mysqli_fetch_array($sql)) {
$product_name = $row['product_name'];
$price = $row['price'];
$detail = $row['details'];


//SOME CODE HERE THAT CAN ALSO INSERT THIS DATA IN customer_orders table
// I tried this code but nothing happens

$insertData = "INSERT INTO customer_orders(name, products, price, date )VALUES ($name, $product_name, $price,now())";
$dataQuery = mysqli_query($con, $insertData);

}
$dynamicDisplay .= '<li>' . $product_name . '</li>';
}
$dynamicDisplay .= '</ol>';
$dynamicDisplay .= 'To';
$dynamicDisplay .= $_SESSION['address'];

}else {
header("location: index.php");
}
?>

Answer

As I stated in comments, string values require them to be quoted.

Your VALUES ($name, $product_name, $price,now())"; will fail you here and needs to reads as:

VALUES ('$name', '$product_name', $price,now())";

However, if there happens to be any characters that MySQL will complain about, such as apostrophes, then that too will throw a syntax error.

Therefore, you will need to escape those values, which is something you should be doing in the first place. A prepared statement will take care of all this and help prevent against an SQL injection

References:

Also make sure the session was started.