我如何获得COUNT(id)的值

时间:2019-04-19 11:58:29

标签: php mysql object

我遇到此对象的问题。我不知道(如果可能)如何获取COUNT(id)的值。

我尝试$req[0]->COUNT(id) but "COUNT()"将其检测为功能。怎么会把它检测为钥匙?

这是一个var_dump($ req):

object(stdClass)[4]
public 'COUNT(id)' => string '1' (length=1)

PHP

$req = $db->query('SELECT COUNT(id) FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"');

if($req == 1){
 $_SESSION['authentificated'] = true;
 $_SESSION['username'] = $username;
}

var_dump($req); 

查询的输出应为01(如果用户已经注册)。

4 个答案:

答案 0 :(得分:3)

1。您需要为COUNT()添加别名

2。查询执行后,您需要获取记录,然后进行比较

执行以下操作:-

$req = $db->query('SELECT COUNT(id) as count FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"');

$result = mysqli_fetch_assoc($req); // sample example,you need to change accordingly
if($result['count'] == 1){
  //your code

}

注意:-

保存普通密码是一个非常糟糕的主意。因此请使用password hashing

您当前的代码对SQL INJECTION而言是完全开放的。为了防止这种情况,请使用prepared statements

mysqli::prepare

PDO::prepare

我将执行以下操作: https://3v4l.org/YOBGX

答案 1 :(得分:1)

这里需要别名,否则它将无法按照您想要的方式捕获该计数值。

$req = $db->query('SELECT COUNT(id) cnt FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"');


var_dump($req); 

答案 2 :(得分:1)

尝试一下-

 $req = mysqli_query($db,'SELECT (COUNT(id)) as countID FROM `users` WHERE username ="'.$username.'" AND password = "'.$password.'"'));
        $row = mysqli_fetch_array($req);
        $countID = $row['countID'];
        if($countID == 1){
         $_SESSION['authentificated'] = true;
         $_SESSION['username'] = $username;
        }

        var_dump($req);

答案 3 :(得分:0)

这是您尚未绑定密钥的解决方案,请参见下文

 $req = $db->query('SELECT COUNT(id) as user_exists FROM `users` WHERE username 
="'.$username.'" AND password = "'.$password.'"');

if($req == 1){
    $_SESSION['authentificated'] = true;
    $_SESSION['username'] = $username;
}

var_dump($req);