PDO/PHP-检查行是否存在 [英] PDO/PHP - Check if row exist
本文介绍了PDO/PHP-检查行是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望有一个条件,以防该行根本不存在.
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.
推荐答案
您可以直接检查返回值.
You can just check the return value directly.
$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)
{
die('nothing found');
}
/*
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Same here
if( ! $rows)
{
die('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()) die('found');
这篇关于PDO/PHP-检查行是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文