0

在课堂上,我有一些 PDO:

$userFName = 'userFName';
include('dbconnect.php');       // Normally I'd store the db connect script outside of webroot
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_password);
$stmt = $pdo->prepare('SELECT userFName FROM Users WHERE username = :uname AND password = :pword AND roleID = 1');
$stmt->bindParam(':uname', $this->user->username);
$stmt->bindParam(':pword', $this->user->password);
$stmt->bindColumn(4, $userFName, PDO::PARAM_STR);
$stmt->execute();
$familiar = $stmt->fetch(PDO::FETCH_BOUND);
$this->user->firstName = $familiar;

它在第一列中返回 ID,而不是在第四列中返回 VARCHAR 内容。知道为什么吗?

4

2 回答 2

1

使用PDO::FETCH_BOUNDwith 时fetch(),该方法不会返回结果记录。相反,列的值应该在您之前绑定的变量中可用$stmt->bindColumn()

因此,将您的代码更改为:

$stmt->bindColumn(1, $userFName, PDO::PARAM_STR);
$stmt->execute();
$stmt->fetch(PDO::FETCH_BOUND);
$this->user->firstName = $userFName; // <-- use the bound variable

但是你不需要那个bindColumn()电话。您可以将代码简化为:

$stmt->execute();
$row = $stmt->fetch(); // uses PDO::FETCH_ASSOC by default
$this->user->firstName = $row['FName'];
于 2013-04-25T23:26:24.830 回答
0

你的课上有太多的代码。还有一个错误。要发送一个不同的查询以仅从数据库中获取一个属性,为此创建一个不同的连接是一种过分的杀伤力。 必须无条件地移走连接,并且您必须考虑通过一次查询获取所有用户数据。

正确的代码

function __construct($pdo) {
    $this->pdo = $pdo;
    // Normally you should include somewhere in a bootstrap file
    // not in the application class
    // and instantiate PDO in that bootstrap as well
    // and only PASS already created instance to the class
}

function getUserFName() {
    $sql = 'SELECT * FROM Users WHERE username = ? AND password = ? AND roleID = 1';
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array($this->user->username,$this->user->password));
    return $stmt->fetchColumn();
}
于 2013-04-26T06:33:00.470 回答