Chr*_*ris 3 php mysql refactoring pdo
谢谢你检查.所有有用的答案/评论都已经过投票.我有以下代码,它完成了这项工作,但是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
}
Run Code Online (Sandbox Code Playgroud)
如何改进它以消除foreach和fetchAll的庞大外观(考虑到我知道它总是只有1或0记录)?但是我仍然需要类似的检查点,所以我可以BLOCK A BLOCK B BLOCK C按照我当前的逻辑需要执行相同的操作.
$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
}
Run Code Online (Sandbox Code Playgroud)