[英]How to effectively replace (mysql_result(mysql_query()) in PDO?
As my process is almost complete for rewriting web with PDO instead of mysql_*
commands I am now testing my changed functions. 由于用PDO代替mysql_*
命令重写Web的过程几乎完成,因此我现在正在测试更改后的功能。 And It seems that my changed function for mysql_result(mysql_query()
always returns true, why is that? Lets see original and changed code: 而且似乎我为mysql_result(mysql_query()
更改的函数总是返回true,为什么呢?让我们看一下原始的和更改的代码:
if (mysql_result(mysql_query("SELECT COUNT(*) FROM account WHERE id='".$_SESSION["user_id"]."' AND online=1"), 0)>0)
{
return true;
}
else
return false;
And changed code here: 并在这里更改代码:
$stmt = $db_login->prepare("SELECT COUNT(*) FROM account WHERE id=:id AND online=1");
$stmt->bindValue(':id', $_SESSION["user_id"], PDO::PARAM_INT);
$stmt->execute();
$results_login = $stmt->fetch(PDO::FETCH_ASSOC);
$rows = count($results_login);
if ($rows > 0)
{
return true;
}
else
return false;
So what is wrong with is why it always returns true even when column has online=0? 那么,哪里出了问题,为什么即使列的online = 0时也总是返回true? Thank you 谢谢
$stmt->fetch
fetches one row from the result set. $stmt->fetch
从结果集中获取一行 。 What you get out of that is an array containing all the selected columns, looking something like this: 您从中得到的是一个包含所有选定列的数组,看起来像这样:
array(
'COUNT(*)' => 42
)
A count()
on that array will always result in 1
. 该数组上的count()
始终为1
。
You need to check the contents of the fetched row: 您需要检查提取的行的内容:
if ($result_login['COUNT(*)'] > 0)
It's best to alias this column to a nicer name: 最好将此列别名为一个更好的名称:
SELECT COUNT(*) AS `count` ...
Then: 然后:
if ($result_login['count'] > 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.