【问题标题】:No results from prepared statement query准备好的语句查询没有结果
【发布时间】:2013-07-14 00:50:18
【问题描述】:

我是 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

我确定我做错了什么(没有人可以责怪,只能怪自己在编程中),但我似乎无法发现它。任何帮助将不胜感激。

作为参考,这里是用于创建用户表的 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;

任何帮助将不胜感激。

【问题讨论】:

    标签: php sql mysqli prepared-statement


    【解决方案1】:

    嗯,对我来说,您的代码似乎可以正常工作...

    我完全按照你说的做了。在构造时,创建语句。尽管您从未提及 $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);
    

    在屏幕上成功打印Retrieved username MyUsername,并且$username 等于MyUsername(您的表中ID=2 的用户名)。

    您的代码似乎可以正常工作?

    【讨论】:

    • 事实证明,是的,该代码特别适用。我缺少的是语句使用之间的重置,因此在第一次调用时我会检索 ID,而随后的调用将失败。感谢您为我提供了一个独立的、可工作的代码块,以帮助我正确地指导我的搜索:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    相关资源
    最近更新 更多