【问题标题】:Learning OOP in PHP, trying to refactor my code. Can't connect to database anymore在 PHP 中学习 OOP,尝试重构我的代码。无法再连接数据库
【发布时间】:2023-03-03 03:41:01
【问题描述】:

以为我了解类的工作原理,然后我尝试了以下代码:

class user
  {
  var $dbcon;

  var $dbinfo;
  var $con;    
  var $error;

  function dbConnect()
    {

    $this->dbinfo['server'] = "localhost";
    $this->dbinfo['database'] = "foolish_faith";
    $this->dbinfo['user'] = "user";
    $this->dbinfo['password'] = "password";

    $this->con = "mysql:host=".$dbinfo['server']."; dbname=".$dbinfo['database'];
    $this->dbcon = new PDO($con, $dbinfo['user'], $dbinfo['password']);
    $this->dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $this->error = $this->dbcon->errorInfo();

    if ($error[0] != "")
      {
      print "Error!";
      print_r($error);
      }
    }
  }

现在它只是吐出这个错误:

致命错误:未捕获的异常 带有消息“无效”的“PDOException” 数据源名称'在 E:\PortableApps\xampp\htdocs\dbcon.php:24 堆栈跟踪:#0 E:\PortableApps\xampp\htdocs\dbcon.php(24): PDO->__construct('', NULL, NULL) #1 E:\PortableApps\xampp\htdocs\login.php(4): user->dbConnect() #2 {main} 抛出 E:\PortableApps\xampp\htdocs\dbcon.php 第 24 行

谁能看出我做错了什么,因为我确信这与我在课堂上缺乏知识有关?

【问题讨论】:

    标签: php oop class pdo


    【解决方案1】:
    $this->con = "mysql:host=".$dbinfo['server']."; dbname=".$dbinfo['database'];
    $this->dbcon = new PDO($con, $dbinfo['user'], $dbinfo['password']);
    

    当您访问类实例的变量时,您必须使用 -> 运算符。在这种情况下,您将使用$this->dbinfo 而不仅仅是$dbinfo$this->con 而不是$con。您在左侧已正确完成,但在右侧错过了一些。

    【讨论】:

      【解决方案2】:

      不要在连接字符串中添加空格。 ("; dbname=" 应该是";dbname=")。

      此外,在某些情况下,您需要在某些类实例变量($this->con$this->dbinfo 等)前添加 $this->

      【讨论】:

        【解决方案3】:

        制作这个:$this->dbcon = new PDO($con, $dbinfo['user'], $dbinfo['password']);
        诠释这个:$this->dbcon = new PDO($this->con, $dbinfo['user'], $dbinfo['password']);

        【讨论】:

          【解决方案4】:

          这里是 dsn 语法:http://fr2.php.net/manual/en/ref.pdo-mysql.connection.php 我没有看到任何空格,也许您应该删除分号后添加的那个...

          【讨论】:

            猜你喜欢
            • 2018-01-30
            • 2012-10-26
            • 2014-01-11
            • 2020-04-15
            • 2020-07-02
            • 2017-07-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多