[英]New SQL PDO query from result
I'm very new to PDO SQL queries. 我是PDO SQL查询的新手。 I have the following code which works well.
我有下面的代码,效果很好。 When the result returns only 1 row, I then want to set that row to
valid = FALSE"
. How do I do that? 当结果仅返回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
}
Yet another solution. 另一个解决方案。
IF you interested in "else" section mentioned above, you can combine elegant solution from @YourCommonSense with checking how much rows was changed in UPDATE. 如果您对上面提到的“其他”部分感兴趣,则可以将@YourCommonSense中的优雅解决方案与检查UPDATE中更改了多少行相结合。 MySQL returns such info!
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
}
I then want to set that row to valid = FALSE". How do I do that?
然后,我想将该行设置为有效= FALSE”。我该怎么做?
this is what SQL is for. 这就是SQL的目的。
$sql = "UPDATE `passcodes` SET `valid` = FALSE WHERE `passcode` = ? AND `valid` = TRUE";
$DBcon->prepare($sql)->execute([$passcode]);
this is all the code you need. 这就是您需要的所有代码。
This will work with count of result rows equal or greater than 1. I recommend to use placeholders for prepared statements: 这将在结果行数等于或大于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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.