我是mysqli的新手,以面向对象的方式使用PHP,并且在使用准备好的语句检索值时遇到了问题。我有一个PHP类,它有一个变量:
var $getUsernameStatement;
在施工期间,我准备声明:
$this->getUsernameStatement = $this->db->prepare("SELECT username FROM users WHERE id = ?;");
然后,稍后,我用它检索一个值:
function getUsername($userID) {
$this->getUsernameStatement->bind_param("i", $userID);
$this->getUsernameStatement->execute();
$this->getUsernameStatement->bind_result($username);
if($this->getUsernameStatement->fetch()) {
echo("Retrieved username " . $username);
} else {
echo("Nope!");
}
return $username;
}
至少这是计划。当我传递一个已知的好ID时,我似乎没有得到任何值,比如:
$user->getUsername(2); // There exists an entry with id 2 in the table
我确信我做错了什么(除了编程中的自己,没有人可以责怪),但我似乎没有发现。任何帮助都将不胜感激。
作为参考,这里是用于创建users表的SQL:
$sql = <<<SQL
CREATE TABLE IF NOT EXISTS `users` (
`id` INT NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(64) NOT NULL ,
`email` VARCHAR(128) NOT NULL ,
`password_hash` VARCHAR(128) NOT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC) ,
UNIQUE INDEX `email_UNIQUE` (`email` ASC) ,
UNIQUE INDEX `username_UNIQUE` (`username` ASC) );
SQL;
如有任何帮助,我们将不胜感激。
对我来说,你的代码似乎在工作。。。
我完全按照你说的做了。构造时,创建语句。虽然您从未说过$db变量,但我假设您在使用它之前,已经在类中定义并初始化了数据库连接?
class TheClass
{
private $db;
private $getUsernameStatement;
function __construct()
{
// Initialise database variable
$this->db = mysqli_connect("host", "username", "password", "dbname");
// Prepare the statement
$this->getUsernameStatement = $this->db->prepare("SELECT username FROM users WHERE id = ?;");
}
// Your function, without changes
public function getUsername($userID) {
$this->getUsernameStatement->bind_param("i", $userID);
$this->getUsernameStatement->execute();
$this->getUsernameStatement->bind_result($username);
if($this->getUsernameStatement->fetch()) {
echo("Retrieved username " . $username);
} else {
echo("Nope!");
}
return $username;
}
}
然后通过实例化类并调用方法来测试它:
$c = new TheClass();
$username = $c->getUsername(2);
成功地在屏幕上打印检索到的用户名MyUsername,$username等于MyUsername(ID为2的表中的用户名)。
你的代码似乎在工作?