扩展 PDO 类
问题描述
以下是我目前推出的数据库连接类,但我将通过扩展 PDO 类本身来改进它,
Below is the db connection class I came out with so far, but I am going to improve it by extending the PDO class itself,
扩展类,
这就是我实例化类的方式,
This is how I instantiate the class,
但是当我调用这个扩展的 pdo 类时出现错误,
But I have errors when I call this extended pdo class,
警告:PDO::__construct() 需要参数 4 为数组,给出字符串在 C:wampwwwxxclass_database.php在线 xx
Warning: PDO::__construct() expects parameter 4 to be array, string given in C:wampwwwxxclass_database.php on line xx
致命错误:调用成员函数setAttribute() 在非对象上C:wampwwwxxclass_database.php 上第 xx 行
Fatal error: Call to a member function setAttribute() on a non-object in C:wampwwwxxclass_database.php on line xx
我在网上做了一些研究,我找到了扩展pdo的这个基本结构,但我不明白......
I have done some research online, I found this basic structure of extending pdo but I dont understand it...
$ds
n 变量有什么用?如何将我的 $hostname
变量传递给扩展的 pdo 类?
What is $ds
n variable for? How can I pass my $hostname
variable into extended pdo class?
另一个问题:如何在扩展的 pdo 类中创建一个显示错误的方法?如何关闭扩展 pdo 类中的连接?
Another questions: How can I make a method for displaying error in the extended pdo class? How can I close the connection in the extended pdo class?
从mysqli迁移到pdo太难了!
It is so difficult to move from mysqli to pdo!
谢谢.
推荐答案
$dsn 是数据源名称.它为您处理您的主机名.你像这样使用它:
$dsn is data source name. It handles your hostname for you. You use it like this:
随着行 $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
你已经设置了在发生错误时引发的异常(我喜欢),所以在你的扩展类,您可以处理异常处理程序中的错误.如果您的扩展 PDO 类中有一个名为 getAssoc 的方法,那么它看起来像这样:
With the line $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
You have set exceptions to be raised when errors occur (which I like), so in your extended class you can handle errors in exception handlers. If you had a method called getAssoc in your extended PDO class then it would look like this:
这篇关于扩展 PDO 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!