我搜索了论坛,但我没有找到任何与我的问题直接相关的内容。我对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用于我的所有类文件
预期行动:
当我的"search.php"页面通过pdo从mysql请求数据时,新的数据库连接将通过"openConnection()"方法实例化一个新连接。
"DatabaseConnection"类将从"db_cred.inc.php"加载凭据作为sting并连接到数据库
然后,该类将使用凭据连接到mysql数据库,并执行请求的pdo查询,返回结果并将它们存储到变量"$ row"中。
问题:
当我执行pdo时,返回以下错误:
未捕获的TypeError:PDO :: __ construct()期望参数1为字符串,私有/ classes / DatabaseConnect.class.php中给出的数组:21堆栈跟踪:#0 private classes DatabaseConnect.class.php(21):PDO- > __ construct(Array)#1 public search.php(53):在第21行的 private classes DatabaseConnect.class.php中抛出的DatabaseConnect-> openConnection()#2 {main}
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"中的凭据设置
// 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",
]);
?>
我的数据库连接类:
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
$dbconn = new DatabaseConnect();
$pdo = $dbconn->openConnection();
$sql ="SELECT * FROM report";
foreach ($pdo->query($sql) as $row) {
echo" PI:".$row['pi'] ."";
}
?>
我不确定导致错误的原因。我确信这是由于我对课程和oop缺乏经验。似乎config.php文件工作正常。该类由请求标识,因为错误发生在PDO __construct方法中。请帮忙。
更新 - 我的工作解决方案
我希望这可能有助于某人向前推进类似的问题。我没有完成这个过程的开发,但这踢了一个巨大的门。
我修改了课程
// 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"消除了数组。我可能会重温这个想法。
// 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",
]);*/
?>
你期望什么,你传递PDO一个数组,只有一个数组。 阅读文档,特别是示例。
松开方括号。
@LawrenceCherone感谢您的回复。 我删除了括号,错误从"Uncaught TypeError:PDO :: __ construct()期望参数1变为字符串"到"Uncaught TypeError:PDO :: __ construct()期望参数4为数组"。
从我已经链接到的文档。 PDO __construct期望...... public PDO::__construct ( string $dsn [, string $username [, string $passwd [, array $options ]]] )
顺便说一下,这仍然会失败,因为$server不是DSN。
为什么不使用现有的PDO包装器? 那里有很多人。 你是出于什么原因重新发明轮子的?
你必须阅读文档才能使用它们:)
感谢您提出的所有建设性意见。 我现在有一个工人阶级。 我用最后的工人阶级更新了帖子。 如果你发现有什么不妥,请告诉我。
错误解释了自己:您正在传递一个数组,您应该使用字符串代替。
您需要更改此行:
$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);
这次真是万分感谢。 我确实改变了一点。 见下文。 //建立DSN $ dsn ="mysql:host = {$ this-> host}; dbname = {$ this-> database}; charset = {$ this-> char}"; //完成PDO连接$ this-> con = new PDO($ dsn,$ this-> user,$ this-> pass,$ this-> opt);
如果我的回答对你有帮助,请接受。 (通过点击复选标记),因为它可能在将来帮助其他人。
我点击了向上箭头。 因为我是新手,它不会显示,但系统确实会计算它。
箭头下方应该有一个复选标记,以接受答案。 它也会给你一些代表。
谢谢......新手在这里。 哈哈