I am still new to learning how MySQL works and PhP and I have been trying to get my Array values which is part of a session into a MySQL database but I can't figure out how to or what I am doing wrong. I can't get the query to grab certain values out of the array in the function checkouttodatabase().
I've tried following multiple tutorials and posts regarding getting a session array posted into a MySQL database but to no avail. This seems to "function" but doesn't add the item name to the database but instead puts down "Array" and the values "0"
//Adding the item to the array
if (isset($_POST["add_to_cart"])) {
if (isset($_SESSION["shopping_cart"])) {
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
if (!in_array($_GET["id"], $item_array_id)) {
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
array_push($_SESSION['shopping_cart'], $item_array);
} else {
echo '<script>alert("Item Already Added")</script>';
echo '<script>window.location="shoppingcart.php"</script>';
}
} else {
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
//Function to grab array values and add it to database
function checkouttodatabase() {
$connect = mysqli_connect("localhost", "root", "", "precisionmice");
mysqli_select_db($connect, 'precisionmice');
foreach($_SESSION['shopping_cart'] as $row => $id){
$sql="INSERT INTO orders (product, quantity, totalprice)
VALUES ('item_id','item_quantity','item_price')";
}
if(mysqli_query($connect, $sql)){
echo "Betaling bevestigen";
header("refresh:2; url=checkout.php");
} else {
echo "Update mislukt";
}
}
The function checkouttodatabase() is called when the player is redirected to a seperate webpage. Now what I would love as a result is so let's say there are two items added to the shoppingcart array. For each item added I would like it to send the variables to the MYSQL database. Except I also struggle for the total price. I would like to do it so that the quantity is multiplied by the individual item_price which is added in the MYSQL column total_price.
For example: Database results when submitted:
Item_id: Productname 1 , Item_quantity: 3, Total_price: 45.00$
Item_id: Productname 2, Item_quantity: 1, Total_price: 15.00$
'item_id'as a string. Instead define that as?,?,?and usebind_paramto set the values.$sqleach and every time, but only insert the last occurence into the database? And why don't you use variables within that query?