Reputation:
im trying to figure out what's wrong with this code. im getting the Call to a member function fetch_assoc() error but I can't figure out why
for the record - im trying to build an eCommerce site for a project in college and with the following code im trying to reduce the item stock when a purchase is made.
Just to mention - I executed the SELECT query in PhpMyAdmin and it worked
<?php
require 'config.php';
session_start();
$sql = "SELECT * FROM cart,product WHERE product.product_code = cart.cart_product_code";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$stock=$row['product_stock']-$row['quantity'];
$id_stock=$row['cart_product_code'];
$sql= "UPDATE product SET product_stock='$stock' WHERE product_code='$id_stock'";
$result = mysqli_query($conn, $sql);
$query="TRUNCATE TABLE Cart";
$clear= mysqli_query($conn, $query) or die("Invalid query");
}
}
Upvotes: 0
Views: 103
Reputation: 455
You are overriding the $result object inside the while loop by querying an update query. You could execute the query without setting any variable :
$sql= "UPDATE product SET product_stock='$stock' WHERE product_code='$id_stock'";
mysqli_query($conn, $sql);
Also, I strongly suggest you to use prepared statement to avoid any form of SQL injection.
Upvotes: 1