0

我第一次尝试为 MySQL 使用准备好的语句,但它没有返回任何数据:

$pdo = new PDO('mysql:dbname=[DBASE];host=localhost', '[USER]', '[PWORD]',
                array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));

$sth = $pdo->prepare('SELECT id FROM users WHERE username = "' . mysql_real_escape_string($_SESSION['myusername']) . '"');
$sth->execute();
$result = $sth->fetch(PDO::FETCH_OBJ);
$user_id = $result->id;

可能很清楚,我正在尝试返回给定用户名的 user_id。有人可以让我知道我做错了什么。谢谢。

4

1 回答 1

1

For what you are trying to do:

$pdo = new PDO('mysql:dbname=[DBASE];host=localhost', '[USER]', '[PWORD]',
                array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));

$sth = $pdo->prepare('SELECT id FROM users WHERE username = ?');

$success = $sth->execute(array($_SESSION['username']));

if ($success) {
    $result = $sth->fetch(PDO::FETCH_OBJ);
    $user_id = $result->id;
} else {
    echo "Query failed.";
    var_dump($sth->errorInfo());
}

You have to prepare a statement using either named or positional parameters. If the prepare was successful, you can then execute queries on that statement. Depending on how you bound the parameters, execute will accept different types of arguments.

If the execution of the statement was successful, you can then read results from it.

More examples in the manual:

于 2012-08-14T19:32:37.363 回答