1

0 から 10 の範囲の値を持つ DB に投票を保存しています。私が抱えている問題は、クエリ基準を満たす投票が 0 の場合、else ステートメントをトリガーすることです。if文を次のように変更すると...

if ($vote >= 0)

...その後、クエリ基準を満たすものがない場合でも、if ステートメントは常に true になります。どうすれば2つを区別できますか?ありがとう。

$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
}
4

1 に答える 1

1

In a loose comparison, NULL will 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 becomes NULL. You should test that before setting $vote to its null value, to avoid undefined index notices. Then check for an integer value of $vote in the if() condition.

// $vote is NULL if $row is not populated
$vote = isset($row['vote']) ? $row['vote'] : NULL;

// Check that $vote is an int value as opposed to NULL
if (is_int($vote) && $vote >= 0) {
  // Code executed when $vote is an integer value
} 
else {
  // Other code to execute if $row was empty 
}

You could also check if $row is an array, meaning your fetch() call produced a row:

if (is_array($row)) {
  // Code using $vote
}
else {
  // No row was returned 
}
于 2012-11-29T02:29:36.640 に答える