未捕获的TypeError:PDO :: __ construct()期望参数1为字符串

时间:2019-02-26 20:43:26

标签: php pdo

我已经搜索了论坛,但是没有发现与我的问题直接相关的任何内容。我对PDO和类OOP的创建还很陌生。我试图创建一个数据库连接类,可以在其中实例化所需的连接。我在实例化我的连接时遇到问题。

文件组织:

parent directory (folder)
      |     
      private (folder)
            |
            config.php
             classes (folder)
                     |
                     class1.class.php
                     DatabaseConnection.class.php
                     db_cred.inc.php
      public (folder)
           |
           search.php

过程:

  • 我已经创建了一个数据库凭证php文件“ db_cred.inc.php”
  • 在“ DatabaseConnect.class.php”文件中有一个名为“ DatabaseConnect”的数据库连接类
  • 我按如下方式加载这些文件
    • require_once'db_cred.inc.php';在“ DatabaseConnect.class.php”文件中
    • 为我所有的班级文件spl_autoload_register

预期的操作:

  1. 当我的“ search.php”页面通过pdo向mysql请求数据时,新的数据库连接将通过“ openConnection()”方法实例化新的连接。
  2. “ DatabaseConnection”类将从字符串“ db_cred.inc.php”中加载凭据,然后连接到数据库
  3. 然后,该类将使用凭据连接到mysql数据库,并执行请求的pdo查询,以返回结果并将其存储到变量“ $ row”中。

问题: 当我执行pdo时,返回以下错误: 未捕获的TypeError:PDO :: __ construct()期望参数1为字符串,在private / classes / DatabaseConnect.class.php:21中给出的数组堆栈跟踪:#0 private \ classes \ DatabaseConnect.class.php(21):PDO- > __ construct(Array)#1 \ public \ search.php(53):DatabaseConnect-> openConnection()#2 {main}在第21行的\ private \ classes \ DatabaseConnect.class.php中抛出

config.php文件中的

spl_autoload_register()

  function my_autoload($class) {
    if(preg_match('/\A\w+\Z/', $class)) {
      require ('classes/' . $class . '.class.php');
    }
  }
  spl_autoload_register('my_autoload');

“ db_cred.inc.php”中的凭据设置

<?php

// define an array for db connection.
define("DB", [
  "DB_HOST" => "mysql:host=localhost",
  "DB_USER" => "user",
  "DB_PASS" => "pass",
  "DB_DATABASE" => "mytestdb",
  "DB_CHAR" => "utf8",
]);
?>

我的数据库连接课程:

<?php
require_once 'db_cred.inc.php';

// creating db connection class

class DatabaseConnect {

private $server = 'DB_HOST';
private $database = 'DB_DATABASE';
private $pass = 'DB_PASS';
private $user = 'DB_USER';
private $opt = [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  PDO::ATTR_EMULATE_PREPARES   => false,
];

protected $con;

public function openConnection() {

**ERROR TAKES PLACE HERE**

  try {
    $this->con = new PDO([$this->server, $this->database, $this->user, $this->pass]);
      return $this->con;
  } catch(PDOExeption $e){
    echo "ERROR: " . $e->getMessage(), (int)$e->getCode();
  }
}
public function closeConnection() {
     $this->con = null;
  }
}

 ?>

用于search.php的PDO

<?php

$dbconn = new DatabaseConnect();
$pdo = $dbconn->openConnection();

$sql = "SELECT * FROM report";
foreach ($pdo->query($sql) as $row) {
  echo " PI: ".$row['pi'] . "<br>";

}
?>

我不确定是什么引起了错误。我确信这是由于我对课程和oop的经验不足。看来config.php文件运行正常。该类由请求标识,因为该错误发生在PDO __construct方法内部。请帮忙。

更新-我的工作解决方案

我希望这可以帮助有人提出类似的问题。我还没有完成这个过程的开发,但是却为这扇门打开了大门。

我的修订课程

<?php
// Associating db_cred.inc.php with class
require_once('db_cred.inc.php');

// Creating db connection class
class DatabaseConnect {
/*
!! Assigning defined constants per define('DB_CONSTANT', 'value') loaded from "db_cred.inc.php" file to variables
!! "db_cred.inc.php" should not be loaded into the "config.php" file
!! BECAUSE THE VALUES OF THE VARIABLES ($variable) ARE CONSTANTS (DB_CONSTANT), DO NOT USE SINGLE OR DOUBLE QUOTES. THE PDO __CONSTRUCT FUNCTION WILL IGNORE  THE VALUE OF THE VARIABLE
*/
private $host =  DB_HOST;
private $database = DB_DATABASE;
private $pass = DB_PASS;
private $user = DB_USER;
private $char = DB_CHAR;
// Setting attributes and storing in variable $opt
private $opt = [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  PDO::ATTR_EMULATE_PREPARES   => false,
];
// $con variable will store PDO connection and is set to NULL
private $con;

// Create Connection to database
public function openConnection() {
  // Setting $con to null
$this->con = NULL;

// If $con is not NULL make it NULL
if ($this->con === NULL){
  try {
    // Establish DSN
    $dsn = "mysql:host={$this->host};dbname={$this->database};charset={$this->char}";
    // Complete the PDO connection
    $this->con = new PDO($dsn, $this->user, $this->pass,$this->opt);
    // Return the connection and store it in $con
      return $this->con;
      // Catch any exceptions and store in $e
  } catch(PDOExeption $e){
    // Echo error and Exception message
    echo "ERROR: " . $e->getMessage(), (int)$e->getCode();
  }
  // If the try/catch block fails, echo that no connection was established
} else {
  echo "ERROR: No connection can be established";
}
}
// Close connection and set it to NULL
public function closeConnection() {
     if($this->con !== NULL){
     $this->con = NULL;
   }
  }

// create CRUD subclass (Create, Read, Update, Delete)
}
 ?>

我更改了“ db_cred.inc.php”,删除了数组。我可能会重新考虑这个想法。

<?php

// defining DB Credential CONSTANTS to be stored in variables and instantiated by connect class
define("DB_HOST", "localhost");
define("DB_USER", "user");
define("DB_PASS", "pass");
define("DB_DATABASE", "mytestdb");
define("DB_CHAR", "utf8");

// define an array for db connection.
/*define("DB", [
  "DB_HOST" => "localhost",
  "DB_USER" => "user",
  "DB_PASS" => "pass",
  "DB_DATABASE" => "mytestdb",
  "DB_CHAR" => "utf8",
]);*/

?>

1 个答案:

答案 0 :(得分:1)

错误说明了自己:您正在传递一个数组,而应该使用字符串。

您需要更改此行:

$this->con = new PDO([$this->server, $this->database, $this->user, $this->pass]);

为此,(首先指定DSN):

$dsn = "mysql:dbname={$this->database};host:{$this->host}";

$this->con = new PDO($dsn, $this->user, $this->password);