如何用 PDO 替换 MySQL 函数
简介:
MySQL 扩展已弃用在 PHP 中,应替换为 MySQLi 或 PDO_MySQL 以实现数据库连接。 PDO(PHP 数据对象)提供了一个现代的、面向对象的接口,用于访问多个数据库。
连接到 MySQL 和 MSSQL 数据库:
MySQL:
$dsn = 'mysql:dbname=database_name;host=localhost'; $user = 'username'; $password = 'password'; $dbh = new PDO($dsn, $user, $password);
MSSQL:
$dsn = 'sqlsrv:Server=localhost;Database=database_name'; $user = 'username'; $password = 'password'; $dbh = new PDO($dsn, $user, $password);
执行查询:
PDO 使用准备好的语句执行查询,防止 SQL 注入。
示例 SQL:
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username';
执行查询:
// Prepare statement with array of named variables $result = $dbh->prepare($SQL); $result->execute([':username' => $username]); // OR // Prepare statement with named placeholder indicator $result = $dbh->prepare($SQL); $result->bindValue(':username', $username); $result->execute();
获取结果:
// Fetch a single row as an array $row = $result->fetch(); // Fetch all rows as an array $rows = $result->fetchAll();
使用辅助类:
要简化数据库交互,请考虑使用如下所示的类:
class PDOConnection { public $connection; public function __construct($dsn, $username, $password) { $this->connection = new PDO($dsn, $username, $password); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } public function query($SQL) { return $this->connection->query($SQL); } public function prepare($SQL, $params = []) { $result = $this->connection->prepare($SQL); $result->execute($params); return $result; } }
用法示例:
$db = new PDOConnection($dsn, $user, $password); $SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username'; $result = $db->prepare($SQL, ['username' => $username]); while ($row = $result->fetch()) { echo $row['ID'] . ' ' . $row['EMAIL']; }
以上是如何用 PDO 替换 MySQL 函数:PHP 中的现代数据库连接指南?的详细内容。更多信息请关注PHP中文网其他相关文章!