I'm trying to insert this information into my database, I have practically the same code setup for SELECT queries and they work. Any INSERT queries I try will not work.
This function returns true, and I've echoed the query this function creates and have used PHPMyAdmin to run the SQL query where it'll show in the database but when doing it through this php code the INSERT never shows up in the database.
EDIT : I noticed that one of my columns (orderID
) that is set to auto increment IS increasing every time I run this function but for whatever reason the query is not actually getting placed into the table.
This Image shows orderID
of 29 is missing, I got those table results by doing 2 PHPMyAdmin INSERT queries, then one with the function and one more with PHPMyAdmin. Is there any way my function could be deleting the insert?
function add_to_cart($user_id, $product_id, $quantity) {
global $mysqli;
if($result = $mysqli->query("INSERT INTO orders (userID, productID, quantity, orderDate) VALUES ('$user_id', '$product_id', '$quantity', NOW())")){
return $result;
}
return false;
}
The user connecting to the database has full privileges to the database so that shouldn't be the issue
I was able to fix the problem by adding $mysqli->commit();
after $mysqli->query()
I needed to do this because I changed the default options and had "SET AUTOCOMMIT = 0"
Taking that out allowed me to remove $mysqli->commit()
function add_to_cart($user_id, $product_id, $quantity) {
global $mysqli;
if($result = $mysqli->query("INSERT INTO orders (userID, productID, quantity, orderDate) VALUES ($user_id, $product_id, $quantity, NOW())")){
if (!$mysqli->commit()) {
print("Transaction commit failed
");
}
return $result;
}
die($mysqli->error());
}
Judging by other numerous questions of the same kind, you are just looking for the results in the wrong database.
Speaking of the function itself, it is bloated and unsafe.
You should use prepared statements.
function add_to_cart($user_id, $product_id, $quantity) {
global $pdo;
$sql = "INSERT INTO orders (userID, productID, quantity, orderDate) VALUES (?, ?, ?, NOW())";
$pdo->prepare($sql)->execute(func_get_args());
}
there is no point in returning anything as in case of error an exception would be thrown. And even if there was, still there is no use for a tautology like IF result == true THEN return true ELSE return false
. You can simply return the result itself.