【问题标题】:Connection to database failure连接到数据库失败
【发布时间】:2016-10-10 06:10:12
【问题描述】:

我似乎无法找出我的数据库或与它的连接的问题。当我尝试运行它时出现此错误。

注意:尝试在第 54 行的 /Applications/XAMPP/xamppfiles/htdocs/swiftappandmysql/db/MySQLDAO.php 中获取非对象的属性

致命错误:/Applications/XAMPP/xamppfiles/htdocs/swiftappandmysql/db/MySQLDAO.php:53 中未捕获的异常“异常”堆栈跟踪:#0 /Applications/XAMPP/xamppfiles/htdocs/swiftappandmysql/scripts/registerUser。 php(41): MySQLDAO->registerUser('email', 'aske', 'meyer', '1bf528e7f15d11c...', 'KO\x8E\xD0\xCE/\xBD\xACK\xD1d\x18\x9A\x07 \xE1...') #1 {main} 在第 53 行的 /Applications/XAMPP/xamppfiles/htdocs/swiftappandmysql/db/MySQLDAO.php 中抛出

连接文件:

<?php class Conn { public static $dbhost = "localhost";
        public static $dbuser = "root";
        public static $dbpass = "";
        public static $dbname = "app";} ?>

MySQL 文件:

public function registerUser($email, $first_name, $last_name, $password, $salt)
{ 
    $sql = "insert into users set email=?, first_name=?, last_name=?, user_password=?, salt=?";
    $statement = $this->conn->prepare($sql);
    if (!$statement)
      throw new Exception($statement->error);
    $statement->bind_param("sssss", $email, $first_name, $last_name, $password, $salt);
    $returnValue = $statement->execute();
    return $returnValue;  
}   

这是第 54 行。if (!$statement) throw new Exception($statement-&gt;error);

【问题讨论】:

  • $statement-&gt;error 应该是 $this-&gt;conn-&gt;error
  • insert into users set email=?,...?您对INSERTUPDATE 操作感到困惑。
  • @Barmar 感谢您的快速回答,尽管我现在收到此致命错误:未捕获的异常 'Exception' with message 'Table 'app.users' doesn't exist in /Applications/XAMPP/xamppfiles /htdocs/swiftappandmysql/db/MySQLDAO.php:54 堆栈跟踪:#0 /Applications/XAMPP/xamppfiles/htdocs/swiftappandmysql/scripts/registerUser.php(41): MySQLDAO->registerUser('email', 'aske', 'meyer', '0ebfe15868c034d...', '\x8FM:\x87\x135j\xC8\xA7\xD7:mH\x88\xF8...') #1 {main} 在 /Applications/XAMPP/xamppfiles/ 中抛出htdocs/swiftappandmysql/db/MySQLDAO.php 第 54 行
  • 那个错误信息似乎很清楚。 app 数据库中没有名为 users 的表。

标签: php mysql database connection


【解决方案1】:

if() 块在 $statement = FALSE 时运行,因此 $statement-&gt;error 不可能是正确的。 error 属性在$this-&gt;conn 中,所以应该是

if (!$statement) {
    throw new Exception($this->conn->error);
}

然后错误消息将显示您的 SQL 的问题。

【讨论】:

  • 嘿@Barmar 我现在收到这个致命错误:我想念我的数据库设置中的 app.users,如下所示 - userID - email - first_name - last_name - user_password - salt & binary.. 我不能看看为什么或在哪里应该实现用户?
  • 使用CREATE TABLE 查询来创建表。或者使用像 PhpMyAdmin 这样的工具来管理你的数据库。