php 为什么这个返回 bool(false)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12181197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is this returning bool(false)?
提问by Colbyd
I have this query that checks if a movement exists and supposed to return true or false. This query
我有这个查询来检查运动是否存在并应该返回真或假。这个查询
function movement_performed_today($class_id, $client_id){
$class_id = (int)$class_id;
$client_id = (int)$client_id;
$query = mysql_query("SELECT COUNT(`movement`) FROM `completed_movements` WHERE `class_id` = '$class_id' AND `client_id` = '$client_id' AND `date` = CURDATE()");
$movement_performed = mysql_fetch_assoc($query);
$return = (mysql_result($movement_performed, 0) == 1) ? true : false;
var_dump ($return);
}
Returns:
返回:
bool(false)
bool(false)
If I replace this code:
如果我替换此代码:
$return = result(mysql_result($movement_performed, 0) == 1) ? true : false;
var_dump ($return);
With this:
有了这个:
print_r ($movement_perfomed);
Returns:
返回:
Array ( [COUNT(`movement`)] => 2 )
Array ( [COUNT(`movement`)] => 3 )
Am I completely wrong to think since these numbers are anything other than zero it should return true?
我是否完全错误地认为这些数字不是零,它应该返回真?
回答by Levi Morrison
To answer your question:
回答你的问题:
mysql_resultreturns FALSEon error. You are passing the array from mysql_fetch_associnstead of the mysql resource as required by mysql_result's function signature:
mysql_resultFALSE错误返回。您正在mysql_fetch_assoc根据mysql_result的函数签名的要求传递数组而不是 mysql 资源:
string mysql_result ( resource $result , int $row [, mixed $field = 0 ] )
Thus it returns FALSEbecause it has an error.
因此它返回,FALSE因为它有一个错误。
A better way:
更好的方法:
// Change
$movement_performed = mysql_fetch_assoc($query);
$return = result(mysql_result($movement_performed, 0) == 1) ? true : false;
// to
$movement_performed = mysql_fetch_row($query);
return $movement_performed[0] > 0;
This grabs the result of the count statement and does a > 0check on it. The > 0check is not really needed but helps show intent rather than relying on on truthy values.
这会获取 count 语句的结果并对其进行> 0检查。该> 0检查是不是真的需要,而且有利于表明意图,而不是依靠上truthy值。
Side note: the mysql_*functions have been deprecated. You should migrate your code to use MySQLior PDO. You are unfortunately using the fact that many mysql_*functions do not need the mysqlresource. Migrating your code will be a pain because you have to change a bunch of functions or declare global variables. I recommend the former option but it will take a lot of effort to fix.
旁注:这些mysql_*功能已被弃用。您应该迁移您的代码以使用MySQLi或PDO。不幸的是,您正在使用许多mysql_*功能不需要mysql资源的事实。迁移您的代码会很痛苦,因为您必须更改一堆函数或声明全局变量。我推荐前一个选项,但需要付出很多努力才能修复。
回答by Sumit Neema
i think it should be
我认为应该是
(count(mysql_fetch_assoc ) >0 ) ? true : false;
rather than
而不是
result(mysql_result($movement_performed, 0) == 1) ? true : false;

