pdo mysql连接类,创建数据库连接类(PDO)并获取数据

I am new to OOP, so I am trying to learn how to create classes and use them. Currently I am trying to fetch data from my MySQL table.

To create the connection with MySQL I am using PDO. I have created a separate class for database connection. I have included the class in my show.php file. Now I want to fetch data from MySQL database. The problem is when I run my show.php file it shows this error message

Fatal error: Call to undefined method DBConnection::prepare() in C:\xampp\htdocs\jm\show.php on line 10`

But it was supposed to display just array.

What is the solution to this problem?

File db.class.php

class DBConnection {

function DBConnection(){

$host = 'localhost';

$dbname = 'srijon';

$user = 'root';

$pass = '';

try {

$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

return $DBH;

}

catch(PDOException $e) {

echo 'ERROR: ' . $e->getMessage();

}

} // function ends

} // class ends

?>

File show.php

require_once 'db.class.php';

function get_all(){

$db = new DBConnection();

$sql = "SELECT * FROM information";

$STH = $db->prepare($sql);

$STH->execute();

$STH->setFetchMode(PDO::FETCH_ASSOC);

return $STH;

}

echo get_all();

?>

解决方案

IMHO you can just inject the PDO connection into the functions that need it:

$dbHandle = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

$dbHandle->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// always disable emulated prepared statement when using the MySQL driver

$dbHandle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

function get_all($dbHandle) {

$sql = "SELECT * FROM information";

$stmt = $dbHandle->prepare($sql);

$stmt->execute();

$stmt->setFetchMode(PDO::FETCH_ASSOC);

return $stmt;

}

get_all($dbHandle);

If you really think you need some class to access to database (other than PDO) (which you don't need) you would have to extend PDO:

class DBConnection extends PDO

{

public function __construct()

{

parent::__construct("mysql:host=$host;dbname=$dbname", $user, $pass);

$this->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// always disable emulated prepared statement when using the MySQL driver

$this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

}

}

$dbHandle = new DBConnection();

function get_all($dbHandle) {

$sql = "SELECT * FROM information";

$stmt = $dbHandle->prepare($sql);

$stmt->execute();

$stmt->setFetchMode(PDO::FETCH_ASSOC);

return $stmt;

}

get_all($dbHandle);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值