PDO 在 php 中不工作

PDO Not Working in php

为什么此代码 returns 错误?

$db = new \PDO('mysql:host=localhost;dbname=apimanager;charset=utf8', 'root', '');      
$q = $db->prepare("select * from tbl_user where username=:u and password=:p");
$q->bindParam(':u',$username,\PDO::PARAM_STR);
$q->bindParam(':p',$password,\PDO::PARAM_STR);
$stmt = $q->fetchAll();     

if(count($stmt)>0)
    return(true);
else
    return(false);

这样使用...

$q=$db->query("select * from tbl_user where username=:u and password=:p");
$stmt = $q->fetchAll();

你的第一行有错误... / 出现在 PDO

之前
$db = new PDO('mysql:host=localhost;dbname=apimanager;charset=utf8', 'root', '');

您只需要在获取数据之前调用 execute(),因为您使用的是准备好的语句,如下所示:

$db = new \PDO('mysql:host=localhost;dbname=apimanager;charset=utf8', 'root', '');      
$q=$db->prepare("select * from tbl_user where username=:u and password=:p");
$q->bindParam(':u',$username,\PDO::PARAM_STR);
$q->bindParam(':p',$password,\PDO::PARAM_STR);
$q->execute();
  //^^^^^^^ See here
$stmt = $q->fetchAll();     

if($stmt)
 //^^^^^ no need for count, if something is in the array it's true otherwise false
    return true;
else
    return false;
        $db = new \PDO('mysql:host=localhost;dbname=apimanager;charset=utf8', 'root', '');      
    $q=$db->prepare("select * from tbl_user where username=:u and password=:p");
    $q->bindParam(':u',$username,\PDO::PARAM_STR);
    $q->bindParam(':p',$password,\PDO::PARAM_STR);
    $q->execute();
    $stmt = $q->fetchAll();     
    //print_r($stmt);
    if(count($stmt)>0)
        return(true);
    else
        return(false);

谢谢它通过插件 $q->execute(); 解决了