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

I have this code:

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

No data is printed but when I copy the result of print $sql into MySQL and run the query (replacing :username with a value that is in that column) I get a result.

Why is this not retrieving data?

Edit: $username comes from a form, so I do:

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

My connection is not the issue, I call a function to return the right connection based on the parameter

$debh = getConnection('read'); // creates connection with user with select privs

Inside getConnection:

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

This works for me:

<?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);
  • Make sure to change the database credentials
  • user@email.com is an user in my database