Migrate from MySQL function to PDO database connection
Introduction
With the deprecation of MySQL functions, it is crucial to turn to alternatives such as PDO for database connections. This article will provide a comprehensive guide on how to implement PDO in MySQL and MSSQL.
Prerequisites
MySQL:
MSSQL:
Create PDO connection
<code class="language-php">$connection = new PDO($dsn, $user, $password);</code>
Use PDO for query
Preprocessing statements:
Get results:
PDO connection example class
<code class="language-php">class Database { protected $connection; public function __construct($dsn, $username, $password) { $this->connection = new PDO($dsn, $username, $password); } public function query($SQL) { return $this->connection->query($SQL); } public function prepare($SQL, $params = []) { $stmt = $this->connection->prepare($SQL); $stmt->execute($params); return $stmt; } }</code>
Examples of usage
<code class="language-php">$db = new Database($dsn, $username, $password); $result = $db->prepare('SELECT * FROM users WHERE username = :username', ['username' => 'john']); while ($row = $result->fetch()) { echo $row['id'] . ' ' . $row['name'] . '<br></br>'; }</code>
The above is the detailed content of How to Replace MySQL Functions with PDO for Database Connections?. For more information, please follow other related articles on the PHP Chinese website!