-1

mysql控制台我有这个

mysql> SELECT `name`, `lastname` FROM `tblStudents` WHERE `idStudent`='2';
+--------------+-----------------+
|     name     |    lastname     |
+--------------+-----------------+
|     Lucio    |    Martínez     |
+--------------+-----------------+
1 row in set (0.00 sec)

所以我想在 PHP 中使用准备好的语句来获取这个学生的姓名和姓氏。

这是代码:

$mysqli = $this->ConnectLowPrivileges();
echo 'Connected<br>';
$stmt = $mysqli->prepare("SELECT `name`, `lastname` FROM `tblStudents` WHERE `idStudent`=?");
if (false==$stmt){
    die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$id = 2;
if ($rc = $stmt->execute(array($id))){
    if ($row = $stmt->fetch()){
        echo "Name: {$row[0]}.<br>Last name: {$row[1]}.<br>";
        echo 'Another way:'.print_r($row);
    }
}
if (false==$rc){
    die('execute() failed: ' . htmlspecialchars($stmt->error));
}
echo 'done';
mysqli_close($mysqli);
return true;

第二个条件给出 false ,我得到的输出是这样的:

Connected
execute() failed: 

PHP 可以毫无问题地与数据库建立连接。

我不知道确切的错误,因为$stmt->error什么都不返回。

4

1 回答 1

0

为避免进一步评论,请阅读我在该问题上发布的所有评论和链接以了解,并将代码更改为:

$mysqli = $this->ConnectLowPrivileges();
echo 'Connected<br>';
$stmt = $mysqli->stmt_init();
$stmt->prepare("SELECT `name`, `lastname` FROM `tblStudents` WHERE `idStudent`=?");

$id = 2;
$stmt->bind_param('i', $id);
if ($stmt->execute()){
    $stmt->bind_result($name, $lastname);
    if ($stmt->fetch()){
        echo "Name: {$name}<br>Last name: {$lastname}<br>";
        //echo 'Another way:'.print_r($row, true); //won't work with bind_result
    } else {
        echo "No results";
    }
} else {
    die('execute() failed: ' . htmlspecialchars($stmt->error));
}
echo 'done';
stmt->close();
$mysqli->close();
于 2013-04-01T20:39:46.010 回答