Home >Database >Mysql Tutorial >How to Replace MySQL Functions with PDO for Database Connections?

How to Replace MySQL Functions with PDO for Database Connections?

Susan Sarandon
Susan SarandonOriginal
2025-01-10 10:40:41647browse

How to Replace MySQL Functions with PDO for Database Connections?

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:

  • PHP module php_pdo_mysql.dll

MSSQL:

  • PHP driver php_pdo_sqlsrv_##_ts.dll or php_pdo_sqlsrv_##_nts.dll

Create PDO connection

<code class="language-php">$connection = new PDO($dsn, $user, $password);</code>

Use PDO for query

Preprocessing statements:

  • Use prepare() to create prepared statements.
  • Bind a value to a placeholder using bindValue() or bindParam().
  • Use execute() to execute statements.

Get results:

  • Use fetch() to get a single row of results.
  • Use fetchAll() to get all row 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!

Statement:
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