【发布时间】:2009-10-15 16:48:22
【问题描述】:
感谢您的检查。所有有用的答案/cmets 都投了赞成票。 我有以下代码,可以完成这项工作,但 imo 效率不高。我认为它效率不高的原因是因为我正在使用 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 记录)?但我仍然需要类似的检查点,所以我可以执行相同的BLOCK ABLOCK BBLOCK C,因为我当前的逻辑需要它。
【问题讨论】:
标签: php mysql refactoring pdo