简体   繁体   中英

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.

I've attached the relevant code here

$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>";
}

I'm sure the solution is fiendlishly simple but I'm new to php and sql and would really appreciate your help!

Maybe this one helps? https://pear.php.net/manual/en/package.database.mdb2.intro-fetch.php

You could use fetchAll() to fetch all results - count() on the response of fetchAll() should do the trick for you.

After you've built up your functionality, I suggest you migrate to some newer stuff, you should not use MDB2 anymore - it's deprecated stuff. https://www.php.net/manual/en/pdo.query.php may be the more modern way to use PHP with mysql.

Otherwise use https://www.php.net/manual/en/mysqli.query.php - you can also retrieve the number of datasets in there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM