我想要一个条件,当该行根本不存在时执行某些操作。
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
尝试了
if (count($row) == 0)
和if($stmt->rowCount() < 0)
,但都不起作用。
直接查看返回值即可。
$stmt = $conn->prepare('SELECT * FROM table WHERE ID=?');
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if( ! $row)
{
echo 'nothing found';
}
/*
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Same here
if( ! $rows)
{
echo 'nothing found';
}
*/
如果您询问检查而不获取,那么只需让MySQL返回一个
1
。您还可以直接在内部绑定变量execute()
:
$sql = 'SELECT 1 from table WHERE id = ? LIMIT 1';
$stmt = $conn->prepare($sql);
$stmt->execute([$_GET['id']]);
if($stmt->fetchColumn()) echo 'found';
if($stmt->rowCount() == 0)
应该可以正常工作,因为在任何情况下行数都不能小于零。
来自手册:
对于大多数数据库,
不会返回 受PDOStatement::rowCount()
语句影响的行数。相反,使用SELECT
发布PDO::query()
相同的声明 谓词作为您想要的SELECT COUNT(*)
语句,然后使用SELECT
检索将要执行的行数 被退回。然后您的应用程序可以执行正确的操作。PDOStatement::fetchColumn()
我建议阅读这里。
这是我在对象类中使用的内容:
function exists_by_id () {
// check if object exists by id
$stm = DB::$pdo->prepare('select count(*) from `table` where `column`=:column');
$stm->bindParam(':column', $this->column);
$stm->execute();
$res = $stm->fetchColumn();
if ($res > 0) {
return true;
}
else {
return false;
}
}