Home > Backend Development > PHP Tutorial > How to Migrate from MySQL Functions to PDO_MySQL?

How to Migrate from MySQL Functions to PDO_MySQL?

Susan Sarandon
Release: 2024-11-26 08:54:10
Original
639 people have browsed it

How to Migrate from MySQL Functions to PDO_MySQL?

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');
    Copy after login
  • MSSQL:

    $dsn = 'sqlsrv:Server=127.0.0.1;Database=databasename';
    $dbh = new PDO($dsn, 'dbuser', 'dbpass');
    Copy after login

Performing Queries:

PDO uses prepared statements, which prevent SQL injection vulnerabilities.

$SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username';
Copy after login

Executing Queries:

Use prepare and execute for variable queries.

$query = $dbh->prepare($SQL);
$query->execute([':username' => 'someone']);
Copy after login

Fetching Results:

Use fetch or fetchAll to retrieve results.

while ($row = $query->fetch()) {
    echo $row['ID'], $row['EMAIL'];
}
Copy after login

Exception Handling:

Enable PDO exception handling.

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Copy after login

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); }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template