How to Replace MySQL Functions with PDO
MySQL functions are now deprecated and will be removed in future PHP versions. MySQLi or PDO_MySQL should be used instead.
PDO Implementation
PDO provides a consistent interface for connecting to different databases, including MySQL and MSSQL.
Connection:
MySQL:
$dsn = 'mysql:dbname=databasename;host=127.0.0.1'; $dbh = new PDO($dsn, 'dbuser', 'dbpass');
MSSQL:
$dsn = 'sqlsrv:Server=127.0.0.1;Database=databasename'; $dbh = new PDO($dsn, 'dbuser', 'dbpass');
Performing Queries:
PDO uses prepared statements, which prevent SQL injection vulnerabilities.
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username';
Executing Queries:
Use prepare and execute for variable queries.
$query = $dbh->prepare($SQL); $query->execute([':username' => 'someone']);
Fetching Results:
Use fetch or fetchAll to retrieve results.
while ($row = $query->fetch()) { echo $row['ID'], $row['EMAIL']; }
Exception Handling:
Enable PDO exception handling.
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Convenience Class:
class PDOConnection { function __construct($dsn, $username, $password) { $this->connection = new PDO($dsn, $username, $password); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); } function query($SQL) { return $this->connection->query($SQL); } function prepare($SQL, $params = []) { return $this->connection->prepare($SQL)->execute($params); } }
The above is the detailed content of How to Migrate from MySQL Functions to PDO_MySQL?. For more information, please follow other related articles on the PHP Chinese website!