I’m storing votes in a DB with values ranging from 0 to 10. The issue I’m having is when the vote that meets the query criteria is 0, it triggers the else statement. If I change the if statement to…
if ($vote >= 0)
…then the if statement is always true even when nothing meets the query criteria. How can I differentiate between the two? Thanks.
$data = array($page_id, $user_id, 'yes');
$STH3 = $DBH->prepare("SELECT vote from votes WHERE page_id = ? and user_id = ? and current = ?");
$STH3->execute($data);
$STH3->setFetchMode(PDO::FETCH_ASSOC);
$row = $STH3->fetch();
$vote = $row['vote'];
if ($vote) {
// some code
}
else {
// some code
}
In a loose comparison,
NULLwill equate to zero. So if nothing meets your criteria and$row['vote']is not populated and you assign its non-existent value to$vote, which becomesNULL. You should test that before setting$voteto its null value, to avoidundefined indexnotices. Then check for an integer value of$votein theif()condition.You could also check if
$rowis an array, meaning yourfetch()call produced a row: