在课堂上,我有一些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而不是第4列中的VARCHAR内容。知道为什么吗?
答案 0 :(得分:1)
将PDO::FETCH_BOUND
与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'];
答案 1 :(得分: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();
}