PDO/PHP - 检查行是否存在

2021-12-26 00:00:00 row php pdo

我想要一个条件,以防该行根本不存在.

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';

相关文章