我是PDO SQL查询的新手。我有以下代码,效果很好。当结果只返回1行时,我想将该行设置为valid = FALSE"
。我该怎么做?
$sql = "SELECT * FROM `passcodes` WHERE `passcode` = '$passcode' AND `valid` = TRUE";
$stmt = $DBcon->prepare($sql);
$stmt->execute();
$count = $stmt->rowCount();
if($count == 1) {
//do this
} else {
//do that
}
答案 0 :(得分:2)
又一种解决方案。
IF 您对"其他"感兴趣上面提到的部分,您可以将@YourCommonSense的优雅解决方案与检查UPDATE中更改的行数相结合。 MySQL返回这样的信息!
$sql = "UPDATE `passcodes` SET `valid` = FALSE WHERE `passcode` = ? AND `valid` = TRUE";
$DBcon->prepare($sql)->execute([$passcode]);
if ($stmt->rowCount() == 0) {
// do this when nothing found
}
答案 1 :(得分:1)
然后我想将该行设置为有效= FALSE“。我该怎么做?
这就是SQL的用途。
$sql = "UPDATE `passcodes` SET `valid` = FALSE WHERE `passcode` = ? AND `valid` = TRUE";
$DBcon->prepare($sql)->execute([$passcode]);
这是您需要的所有代码。
答案 2 :(得分:-1)
这将适用于等于或大于1的结果行数。 我建议使用占位符来准备语句:
$sql = "SELECT `id` FROM `passcodes` WHERE `passcode` = ? AND `valid` = TRUE";
$stmt = $DBcon->prepare($sql);
$stmt->execute([ $passcode ]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($rows) {
//do this
$sql = "UPDATE `passcodes` SET `valid` = FALSE WHERE `id` = ?";
$stmt = $DBcon->prepare($sql);
foreach ($rows as $r) {
$stmt->execute([ $r['id'] ]);
}
} else {
//do that
}