【问题标题】:PHP MySQLi bind_result null?PHP MySQLi bind_result null?
【发布时间】:2013-08-19 07:14:17
【问题描述】:

我正在编写一个类,但我卡在了一个函数中。它通过用户名请求电子邮件地址,但它只返回 null。

代码:

private function getUserEmail($username){
    if($stmt = $this->_mysqli->prepare("SELECT email FROM users WHERE username='?'")){
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->bind_result($email);
        $stmt->fetch();
        var_dump($email);
        $stmt->close();
        return $email;
    }
}

【问题讨论】:

  • 您是否检查了查询是否实际执行?实际上返回任何数据?您的代码只是假设自始至终都是成功的。
  • @MarcB $stmt->execute() 返回 true。
  • 我检查了 $stmt->fetch 是否返回错误,但它返回 null,所以我认为问题出在哪里。
  • 从 ->fetch() 调用中获取 null 意味着根本没有数据(或者您已经获取了所有可用数据):php.net/manual/en/mysqli-stmt.fetch.php。在 ->execute() 调用之后立即执行echo $stmt->num_rows()。如果你得到 0,那么你根本就没有数据。
  • 返回0,但users表中有数据。

标签: php mysqli null return


【解决方案1】:

尝试删除 ? 周围的单引号

if($stmt = $this->_mysqli->prepare("SELECT email FROM users WHERE username=?")){

否则它不会识别 ?作为占位符。

参见documentation on syntax here:“? 字符不应包含在引号内,即使您打算将它们绑定到字符串值。”

【讨论】:

  • 哇,感谢您的帮助。我删除了quations,现在代码可以工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多