本文介紹了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.
推薦答案
直接查看返回值即可.
$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模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!