谢谢你的检查。所有有帮助的答案/评论都会被投票。
我有下面的代码,这项工作,但我是没有效率的。我认为它不高效的原因是因为我正在使用fetchall+循环,尽管我知道查询将返回1或没有记录。
//assume the usual new PDO, binding, and execute are up here
$myval = "somevalue";
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!$res) {
//no record matches
//BLOCK A CODE HERE
} else {
//found matching record (but always going to be 1 record, no more)
foreach($res as $row) {
if ($myval == $row['val']){
//myval is the same as db
//BLOCK B CODE HERE
} else {
//myval is different from db
//BLOCK C CODE HERE
}
}//foreach
}
如何改进它以消除foreach和fetchall的笨重外观(考虑到我知道它总是只有1或0条记录)?但我仍然需要类似的检查点,这样我就可以执行当前逻辑所需的相同检查点。
最佳答案
$myval = "somevalue";
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
//no record matches
//BLOCK A CODE HERE
} else if ($myval == $row['val']) {
//myval is the same as db
//BLOCK B CODE HERE
} else {
//myval is different from db
//BLOCK C CODE HERE
}