I’m using mysqli prepared statements in an OOP manner. Everything is working as intended, but I can’t seem to find any documentation on how to detect and then throw an exception during a while loop. This how my code stands at the moment and it works perfectly.
$rslt=array();
$data=array();
$stmt->bind_result($rslt['col1'], $rslt['col2'], $rslt['col3'], $rslt['col4']);
while($stmt->fetch()){
$data[]=$rslt;
}
However it contains no way of throwing an exception. This is how I throw an exception in a similar script which is limited to 1 result (therefore I don’t need to loop through them on this example).
$rslt=array();
$data=array();
$stmt->bind_result($rslt['col1'], $rslt['col2'], $rslt['col3'], $rslt['col4']);
if(!$stmt->fetch()){
throw new Exception('Failed to fetch results', 1);
}
$data[]=$rslt;
I’m almost trying to do what is in the code below but it throws the following error:-
“Parse error: syntax error, unexpected T_THROW in xxx/xxx/includes/_xxxClass.php on line 95
while($stmt->fetch()){
$data[]=$rslt or throw new Exception('Failed to fetch results', 1);
}
What I’m looking for is a way to see if there is an error with fetching the results and then throw an exception inside my while loop.
Thanks in advance!
The test you are performing is flawed.
mysqli::fetch()returns false on failure, so your while loop will exit as soon as it sees false. If no results are returned, then the loop will not execute and $data will be empty.What you need to do instead is test if $data is populated after the while loop and then throw your exception if it is empty:-
On reflection, you shouldn’t be throwing an exception just because no results are returned, just return the empty array:-
Exceptions are for handling exceptional circumstances and an empty result set is not exceptional.