Home > Article > Backend Development > How to Replace MySQL Functions with PDO: A Guide to Modern Database Connectivity in PHP?
How to Replace MySQL Functions with PDO
Introduction:
The MySQL extension is deprecated in PHP and should be replaced with either MySQLi or PDO_MySQL for database connectivity. PDO (PHP Data Objects) offers a modern, object-oriented interface for accessing multiple databases.
Connecting to MySQL and MSSQL Databases:
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);
Performing Queries:
PDO uses prepared statements for query execution, protecting against SQL injection.
Example SQL:
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username';
Executing a Query:
// 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();
Fetching Results:
// Fetch a single row as an array $row = $result->fetch(); // Fetch all rows as an array $rows = $result->fetchAll();
Using a Helper Class:
To simplify database interactions, consider using a class like the following:
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; } }
Example Usage:
$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']; }
The above is the detailed content of How to Replace MySQL Functions with PDO: A Guide to Modern Database Connectivity in PHP?. For more information, please follow other related articles on the PHP Chinese website!