I have this PHP code that runs a query. The result from "count" is 0, hence, it should enter "else". However, even if it does, what I get is the error "Undefined offset: 0" and "Trying to get property 'num_rows' of non-object" on $sql14, because the array is empty and doesn't have the index provided. This part of the code shouldn't run, however it is running.
What can I do to prevent this? I've added the else part to return that there's no values in the database but, since there's an error on $sql14, it doesn't get printed out.
$sql12 = "SELECT COUNT(idItem) as count
FROM items, type
WHERE type_description = 'jacket'
AND items.type = type.idType;";
$fetched12 = $conn -> query($sql12);
if($fetched12 -> num_rows > 0){
while($row12 = $fetched12 -> fetch_assoc()){
$jacket_count = $row12['count'];
$random = rand(1, $jacket_count-1);
$sql13 = "SELECT * FROM items, type WHERE type_description = 'jacket' AND items.type = type.idType;";
$fetched13 = $conn -> query($sql13);
if($fetched13 -> num_rows > 0){
while($row13 = $fetched13 -> fetch_assoc()){
array_push($all_jackets, $row13['idItem']);
}
}
}
$sql14 = "SELECT * FROM items WHERE idItem = ".$all_jackets[$random].";";
$fetched14 = $conn -> query($sql14);
if($fetched14 -> num_rows > 0){
while($row14 = $fetched14 -> fetch_assoc()){
$id_jacket = $row14['idItem'];
$jacket = $row14['item_description'];
}
}
} else {
$jacket = "no jackets on database";
}
CodePudding user response:
$fetched12 -> num_rows
is a number of fetched rows
And in your case number of fetched rows is 1
. Ands this row is
count |
---|
0 |
You should use value of count
but not number of rows