如何有效地替换PDO中的(mysql_result(mysql_query())? [英] How to effectively replace (mysql_result(mysql_query()) in PDO?

查看:94
本文介绍了如何有效地替换PDO中的(mysql_result(mysql_query())?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于用PDO代替mysql_*命令重写Web的过程几乎已经完成,因此我现在正在测试更改后的功能.而且看来,我为mysql_result(mysql_query()更改的函数始终返回true,这是为什么呢?让我们看一下原始代码和更改后的代码:

As my process is almost complete for rewriting web with PDO instead of mysql_* commands I am now testing my changed functions. And It seems that my changed function for mysql_result(mysql_query() always returns true, why is that? Lets see original and changed code:

if (mysql_result(mysql_query("SELECT COUNT(*) FROM account WHERE id='".$_SESSION["user_id"]."' AND online=1"), 0)>0)
{
  return true; 
}
else
  return false;

并在此处更改了代码:

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

那么问题是为什么即使列的online = 0时也总是返回true?谢谢

So what is wrong with is why it always returns true even when column has online=0? Thank you

推荐答案

$stmt->fetch从结果集中获取一行.从中得到的是一个包含所有选定列的数组,看起来像这样:

$stmt->fetch fetches one row from the result set. What you get out of that is an array containing all the selected columns, looking something like this:

array(
    'COUNT(*)' => 42
)

该数组上的count()始终会导致1.

A count() on that array will always result in 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` ...

然后:

if ($result_login['count'] > 0)

这篇关于如何有效地替换PDO中的(mysql_result(mysql_query())?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆