Php 此PDO语句返回的是整数而不是字符串

Php 此PDO语句返回的是整数而不是字符串,php,mysql,pdo,prepared-statement,Php,Mysql,Pdo,Prepared Statement,在课堂上,我有一些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 us

在课堂上,我有一些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内容。知道为什么吗?

当使用
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

你们班的代码太多了。还有一个缺点。发送一个不同的查询从数据库中只获取一个属性,创建一个不同的连接,因为这是一个非常过分的操作。 连接必须无条件地移开,并且您必须考虑通过一个查询获取所有用户数据

正确代码

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();
}

因为我在你的结果集中只看到了一列,我很惊讶你竟然得到了什么?您不只是将
$this->user->firstName
设置为
true
(FETCH\u BOUND的结果),并在转换为string或int时看到如1所示的情况吗?看起来您正在选择一列并绑定到(不存在的)第四列。它不应该是
$stmt->bindColumn(1,$userFName,PDO::PARAM_STR)?我选择了SELECT*并且它做了同样的事情。所以。。。对列使用
1
,并使用
$this->user->firstName=$userFName
,而不是
$this->user->firstName=$theResultOfYourExecute..@monicale:您的抓取很好。但是您绑定了变量,所以为了检查
fetch()
的结果是否为
true
,其中没有来自结果集的数据。看起来很酷,但应该是第1列而不是第4列。或者,使用列名。我现在明白了,这是问题代码中的另一个错误。已将
4
替换为
1
。谢谢你指出这一点!感谢您也提供了一个替代(较短的)方法。触感很好。你看过问题了吗?你的回答有什么好处?
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();
}