PDO结果为空,但查询通过MySQL返回数据

时间:2015-03-02 05:09:36

标签: php mysql pdo

我有这段代码:

$sql = "SELECT Username,Level FROM users WHERE Username = :username";
print $sql;
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':username' => $username));
$data = $sth->fetchAll();
print_r($data);

没有打印数据但是当我将print $ sql的结果复制到MySQL并运行查询(替换:用该列中的值替换:username)时,我得到了一个结果。

为什么这不会检索数据?

编辑:$ username来自表单,所以我这样做:

$username = $_POST['username']; // print $username shows entered value

我的连接不是问题,我调用函数来根据参数

返回正确的连接
$debh = getConnection('read'); // creates connection with user with select privs

在getConnection内部:

    case "read":
        $connection = new PDO('mysql:host=' . $host . ';dbname=' . $dbName . '', "$readUser", "$readUserPassword");
        break;

1 个答案:

答案 0 :(得分:0)

这对我有用:

<?php
$username = 'user@email.com';
$dbh = new PDO('mysql:host=localhost;dbname=stackoverflow;charset=utf8', 'user', 'password');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT Username,Level FROM users WHERE Username = :username";
print $sql;
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':username' => $username));
$data = $sth->fetchAll();
print_r($data);
  • 确保更改数据库凭据
  • user@email.com是我数据库中的用户