簡體   English   中英

檢查 sql 查詢是否在 PHP 中有任何結果

[英]Checking if sql query has any results in PHP

I'm trying to check if an sql query brings back any results in PHP, I've tried using mysql_num_rows($res) but I keep getting an error saying that the function expected parameter to be a resource but it is instead getting an object .

我在這里附上了相關代碼

$dsn = "mysql://$username:$password@$host/$dbName"; 

require_once('MDB2.php');    

$db =& MDB2::connect($dsn);

if(PEAR::isError($db)){ 
    die($db->getMessage());
}

$sql=//sql query

$res =& $db->query($sql);
if(PEAR::isError($res)){
    die($res->getMessage());
}

$resultsFound = false; 

if (mysql_num_rows($res)>0){
while($row=$res->fetchRow()){
    //insert results here
}
} else {
     echo "<br><h2>Sorry, invalid input</h2>";
}

我確信解決方案非常簡單,但我是 php 和 sql 的新手,非常感謝您的幫助!

也許這個有幫助? https://pear.php.net/manual/en/package.database.mdb2.intro-fetch.php

您可以使用 fetchAll() 來獲取所有結果 - count() 對 fetchAll() 的響應應該可以為您解決問題。

在你建立了你的功能之后,我建議你遷移到一些更新的東西,你不應該再使用 MDB2——它已經被棄用了。 https://www.php.net/manual/en/pdo.query.php may be the more modern way to use PHP with mysql.

否則使用https://www.php.net/manual/en/mysqli.query.php - 您還可以檢索其中的數據集數量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM