简介
PHP 的 mysql 扩展已弃用,将来将被删除。作为替代方案,建议使用 PDO(PHP 数据对象)扩展来连接 MySQL 和其他数据库。本文提供了如何用 PDO 替换 mysql 函数的指南。
为什么转换为 PDO?
连接到MySQL
$dsn = 'mysql:dbname=databasename;host=127.0.0.1'; $user = 'dbuser'; $password = 'dbpass'; $connection = new PDO($dsn, $user, $password); $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
连接到 MSSQL
$dsn = 'sqlsrv:Server=127.0.0.1;Database=databasename'; $user = 'dbuser'; $password = 'dbpass'; $connection = new PDO($dsn, $user, $password); $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
执行查询
PDO 使用准备好的语句来避免SQL注入
$SQL = 'SELECT ID, EMAIL FROM users WHERE name = :username'; $stmt = $connection->prepare($SQL); $stmt->execute([':username' => 'someone']);
$SQL = 'SELECT ID, EMAIL FROM users WHERE name = ?'; $stmt = $connection->prepare($SQL); $stmt->execute(['someone']);
获取结果
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
示例类
一个简单的 PDO连接类封装常用操作:
class PdoConnection { public function __construct($dsn, $user, $password, $options = []) { // ... initialize connection } public function query($sql) { // ... execute query and return result } public function prepare($sql, $params = []) { // ... execute prepared query and return result } }
以上是如何用 PDO 替换 MySQL 函数以提高安全性和性能?的详细内容。更多信息请关注PHP中文网其他相关文章!