Proper way to ask if mysql_num_rows in PHP

自闭症网瘾萝莉.ら 提交于 2019-12-12 08:16:20

问题


Because mysql_num_rows returns false if there are no rows returned, would it be best to do:

$query = mysql_query("SELECT id FROM table WHERE something = 'this'"); 
$result = mysql_num_rows($query);

if ($result) { }

Or should I do:

if ($result >= 1) { }

回答1:


The proper one

$result = mysql_query("SELECT id FROM table WHERE something = 'this'"); 
if (mysql_num_rows($result)){
    //there are results
}

however, you could do this easier, without checking

$result = mysql_query("SELECT id FROM table WHERE something = 'this'"); 
while($row = mysql_fetch_assoc($result))
    //there are results
}

Please. Give your variables proper names




回答2:


The proper way would be using PDO instead of the ancient mysql_* functions:

$stmt = $dbh->prepare('SELECT item_id FROM Items WHERE name = :param');
$stmt->bindParam( ':param', $some_name, PDO::PARAM_STR, 127 );
if ( $stmt->execute() )
{
   echo $stmt->rowCount();
   var_dump( $stmt->fetchAll( PDO::FETCH_ASSOC ));
}



回答3:


It doesn't return false if no rows are returned, it returns false in the case of an error. You can handle that this way:

 if ($result === false) {
    /* An error occurred - do something */
 } else {
    /* $result is set to some number >= 0 */
 }



回答4:


I think honestly that

$query = mysql_query("SELECT id FROM table WHERE something = 'this'"); 
if (mysql_num_rows($query)!==FALSE){
    //there are results
}

is more appropriate.




回答5:


Count will return a value, and you cannot count and then call mysql_num_rows. It is either one of the other.

You could do

$isExist = mysql_query("Select count(id) from ..."); 
$r = mysql_fetch_array($isExist);
if($r['COUNT(id)'] > 0){
//item exists
}else{
//item doesnt exist
}

If alternatively you can do the query as:

$isexist = mysql_query("select * from wcddl_filehosts where downloadid = '".$download[id]."'");
if(mysql_num_rows($isExists)>0){
//we have items
}else{
//we dont have items
}


来源:https://stackoverflow.com/questions/7767684/proper-way-to-ask-if-mysql-num-rows-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!