PDO/PHP - 检查行是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11974613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PDO/PHP - Check if row exist
提问by xperator
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);
Tried if (count($row) == 0)and if($stmt->rowCount() < 0)but none of them works.
尝试过if (count($row) == 0),if($stmt->rowCount() < 0)但没有一个有效。
回答by Xeoncross
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');
}
*/
If you are asking about checking without fetchingthen simply have MySQL return a 1(or use the COUNT()command).
如果您问的是检查而不获取,那么只需让 MySQL 返回 a 1(或使用COUNT()命令)。
$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');
回答by DannyCruzeira
if($stmt->rowCount() == 0)
should work fine, since the number of rows can't be less than zero in any event at all.
应该可以正常工作,因为行数在任何情况下都不能小于零。
From the manual:
从手册:
For most databases,
PDOStatement::rowCount()does not return the number of rows affected by aSELECTstatement. Instead, usePDO::query()to issue aSELECT COUNT(*)statement with the same predicates as your intendedSELECTstatement, then usePDOStatement::fetchColumn()to retrieve the number of rows that will be returned. Your application can then perform the correct action.
对于大多数数据库,
PDOStatement::rowCount()不返回受SELECT语句影响的行数。相反,用于PDO::query()发出SELECT COUNT(*)与预期语句具有相同谓词的SELECT语句,然后用于PDOStatement::fetchColumn()检索将返回的行数。然后您的应用程序可以执行正确的操作。
I would suggest reading up on that here.
我建议在这里阅读。
回答by kjdion84
Heres what I use in my object classes:
这是我在对象类中使用的内容:
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;
}
}

