Introduction
The mysql extension for PHP is deprecated and will be removed in the future. As an alternative, the PDO (PHP Data Objects) extension is recommended for connecting to MySQL and other databases. This article provides a guide on how to replace mysql functions with PDO.
Why Convert to PDO?
Connecting to 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);
Connecting to 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);
Performing Queries
PDO uses prepared statements to avoid SQL injection vulnerabilities.
$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']);
Fetching Results
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Example Class
A simple PDO connection class to encapsulate common operations:
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 } }
The above is the detailed content of How can I replace MySQL functions with PDO for improved security and performance?. For more information, please follow other related articles on the PHP Chinese website!