繁体   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