PDO不能在php中工作

时间:2015-02-28 07:18:51

标签: php pdo

为什么此代码返回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);
$stmt = $q->fetchAll();     

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

3 个答案:

答案 0 :(得分:0)

以这种方式使用......

$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', '');

答案 1 :(得分:0)

您需要在获取数据之前调用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;

答案 2 :(得分:0)

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

谢谢你通过addin $ q-> execute();