gpt4 book ai didi

php - PHP中的PDO,如何改进这个PDO mysql代码

转载 作者:可可西里 更新时间:2023-11-01 07:47:27 25 4
gpt4 key购买 nike

感谢检查。所有有用的答案/评论都已投票。我有以下代码,可以完成工作,但 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 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
}

关于php - PHP中的PDO,如何改进这个PDO mysql代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1573646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com