问题
This seems to always return 1 for $item_result->num_rows; even though there are 0 rows in the DB. However, if an item exists it updates the row correctly. I'm sure something is wrong with my syntax but I'm having a hard time wrapping my head around this mysqli.
$item_query = "SELECT COUNT(*) FROM `rel` WHERE `cart_id` = '".$cartId."' && `id_item` = '".$item_id."'";
$item_result = $mysqli->query($item_query) or die($mysqli->error.__LINE__);
if($item_result->num_rows==1) {
$item_query2 = "SELECT * FROM `rel` WHERE `cart_id` = '".$cartId."' && `id_item` = '".$item_id."'";
$item_result2 = $mysqli->query($item_query2) or die($mysqli->error.__LINE__);
$getOldItems = $item_result2->fetch_array();
$oldQty = $getOldItems['amount'];
$oldNotes = $getOldItems['notes'];
$newQty = $oldQty + $item_quantity;
$newNotes = $oldNotes . $item_notes;
$update_qty = $mysqli->query("UPDATE rel SET amount = '$newQty', notes = '$newNotes' WHERE `cart_id` = '$cartId' && `id_item` = '$item_id'");
if(!$update_qty){
printf("Errormessage: %s\n", $mysqli->error);
}
header('Location: ./ordernew.php');
} else {
$insert_cart_item = $mysqli->query("INSERT INTO rel (`email`, `cart_id`, `id_item`, `amount`, `notes`) VALUES ('$email', '$cartId', '$item_id', '$item_quantity', '$item_notes')");
if(!$insert_cart_item) {
printf("Errormessage: %s\n", $mysqli->error);
}
header('Location: ./ordernew.php');
}
回答1:
When you do SELECT COUNT(*)
there will always be at least one result. Even if its 0.
You will need to fetch the result of the query to get the correct count.
来源:https://stackoverflow.com/questions/14669205/mysqli-num-rows-always-returns-1