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

问题描述 投票:0回答:1

我搜索了论坛,但我没有找到任何与我的问题直接相关的内容。我对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”加载凭据作为sting并连接到数据库
  3. 然后,该类将使用凭据连接到mysql数据库,并执行请求的pdo查询,返回结果并将它们存储到变量“$ row”中。

问题:当我执行pdo时,返回以下错误:Uncaught 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()#main {main}抛出\ private \ classes \ DatabaseConnect第21行的.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;
  }
}

 ?>

PDO for search.php

<?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",
]);*/

?>
php pdo
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.