我想要一个条件,以防该行根本不存在.
I want to have a condition incase the row doesn't exist at all.
$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)
但它们都不起作用.
Tried if (count($row) == 0)
and if($stmt->rowCount() < 0)
but none of them works.
直接查看返回值即可.
$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
(或使用 COUNT()
命令).
If you are asking about checking without fetching then simply have MySQL return a 1
(or use the COUNT()
command).
$sql = 'SELECT 1 from table WHERE id = ? LIMIT 1';
//$sql = 'SELECT COUNT(*) from table WHERE param = ?'; // for checking >1 records
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
if($stmt->fetchColumn()) echo 'found';
这篇关于PDO/PHP - 检查行是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!