2 回答
TA贡献1891条经验 获得超3个赞
首先,这个类 DB_Connect完全没有意义。理论上它添加了一些抽象的“抽象”,但实际上它只是一段无用的代码。所以只是摆脱它。
然后创建一个名为的文件pdo.php并添加以下代码(基于我的How to connect to MySQL using PDO canonical example):
$host = '127.0.0.1';
$db = 'dbname';
$user = 'username';
$pass = 'password';
$charset = 'utf8mb4';
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$pdo = new \PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
然后只需将此文件包含在需要数据库交互的任何脚本中:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/includes/pdo.php';
$stmt = $pdo->query("SELECT `column1` FROM `Table1` ");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
注意那个$_SERVER['DOCUMENT_ROOT']东西。它用于使您的文件可从任何目录使用。我在另一篇关于使用正确文件系统路径的文章中对此进行了解释
TA贡献1784条经验 获得超8个赞
class DB_PDO_Connect {
private $db;
// Connecting to database
public function connect() {
if(!isset($this->db)){
require_once 'include/Config.php';
$this->db = new PDO("mysql:dbname=DB_DATABASE;host=DB_HOST;", DB_USER, DB_PASSWORD,
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
$this->db->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL );
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); // debug
}
return $this->db;
}
}
用
$myPDO =new DB_PDO_Connect();
$conn=$myPDO->connect();
$stmt = $conn->prepare("SELECT `column1` FROM `Table1` ");
//...
- 2 回答
- 0 关注
- 671 浏览
添加回答
举报