Skip to content
</> Mücahit TopalA developer's notebook

Blog/PHP & MySQL

Migrating from the Old mysql_* Functions to PDO: A Step-by-Step Guide

Mücahit Topal 7 min read 3 views TREN

Migrating from the Old mysql_* Functions to PDO: A Step-by-Step Guide

If you have a site that was written years ago, still works, but shows a blank white page as soon as the server's PHP version is upgraded, the cause is most likely the same one every time: mysql_connect, mysql_query, mysql_fetch_array. These functions were deprecated in PHP 5.5 and removed from the language entirely in PHP 7.0. On a current PHP version the code simply does not run; you get "Call to undefined function mysql_connect()".

Below is how I move that kind of code to PDO, step by step. The goal is not to rewrite everything; it is to make a working site safe, file by file, without breaking it.

Why PDO, and why now?

The forced reason is the version: the old extension is gone. The real gain, though, is security. Legacy code typically looks like this:

$id = $_GET['id'];
$result = mysql_query("SELECT * FROM posts WHERE id = $id");
while ($row = mysql_fetch_assoc($result)) {
    echo $row['title'];
}

A value coming from the user is pasted straight into the query text. Anyone who types id=1 OR 1=1 into the address bar can change what the query means. PDO's prepared statements fix this at the root: the query text and the data travel to the database separately, and the data is never interpreted as SQL.

mysqli is an alternative and it supports prepared statements too. I prefer PDO: named placeholders (:id) are readable, errors are handled with exceptions, and the same interface works with other databases. If you will only ever use MySQL, mysqli is not a wrong choice either.

Create the connection in one file

The first job is to move the connection into a single file. In old projects the connection lines are usually copied to the top of every page, and that is exactly what makes a migration painful.

<?php
// db.php
$dsn = 'mysql:host=localhost;dbname=blog;charset=utf8mb4';

$pdo = new PDO($dsn, 'db_user', 'db_password', [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
]);

Each of the three options earns its place:

  • ERRMODE_EXCEPTION: A failing query throws an exception instead of quietly returning false. This has been the default since PHP 8.0, but stating it explicitly guarantees the same behaviour on older versions.
  • FETCH_ASSOC: Rows come back keyed by column name only. With the default setting every column arrives twice, once by name and once by index.
  • EMULATE_PREPARES false: MySQL really prepares the statement instead of PHP imitating it.

Do not skip charset=utf8mb4 in the DSN. It replaces the mysql_query("SET NAMES utf8") line in the old code. And if you can, keep the password out of the code, in a config file outside the web root or in an environment variable.

What replaces what?

This is the table I look at most while migrating:

Old codePDO equivalent
mysql_connect + mysql_select_dbnew PDO($dsn, ...)
mysql_query (with variables)$pdo->prepare() + execute()
mysql_query (fixed text)$pdo->query()
mysql_fetch_assoc$stmt->fetch()
all rows in a while loop$stmt->fetchAll() or foreach ($stmt as $row)
mysql_result($r, 0)$stmt->fetchColumn()
mysql_insert_id$pdo->lastInsertId()
mysql_affected_rows$stmt->rowCount()
mysql_real_escape_stringNot needed; use placeholders
mysql_errorPDOException

The legacy example above becomes:

<?php
require __DIR__ . '/db.php';

$id = (int) ($_GET['id'] ?? 0);

$stmt = $pdo->prepare('SELECT id, title, body FROM posts WHERE id = :id');
$stmt->execute(['id' => $id]);
$post = $stmt->fetch();

if ($post === false) {
    http_response_code(404);
    exit('Post not found.');
}

echo htmlspecialchars($post['title'], ENT_QUOTES, 'UTF-8');

Two things to notice. First, fetch() returns false when there is no row; use it as an array without checking and you get a warning. Second, a prepared statement only protects the database; you still need htmlspecialchars when printing to the page. These are two separate problems with two separate solutions.

Inserts, updates and transactions

Write queries follow the same pattern. The "escape it first, then wrap it in quotes" chain that fills legacy code disappears completely:

$stmt = $pdo->prepare(
    'INSERT INTO comments (post_id, author, body, created_at)
     VALUES (:post_id, :author, :body, NOW())'
);
$stmt->execute([
    'post_id' => $postId,
    'author'  => $author,
    'body'    => $body,
]);
$commentId = (int) $pdo->lastInsertId();

When several writes depend on each other (inserting a comment and incrementing the post's comment count, for example), wrap them in a transaction. Hardly anyone did this with the old extension; with PDO it is three lines:

try {
    $pdo->beginTransaction();

    $pdo->prepare('INSERT INTO comments (post_id, body) VALUES (?, ?)')
        ->execute([$postId, $body]);
    $pdo->prepare('UPDATE posts SET comment_count = comment_count + 1 WHERE id = ?')
        ->execute([$postId]);

    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    throw $e;
}

One note here: transactions work on InnoDB tables. Very old databases may still have MyISAM tables, and there rollBack undoes nothing.

In what order should you migrate?

Trying to change everything in one day on a large project is the shortest route to a broken site. This is the order I follow:

  1. Take inventory. Run grep -rn "mysql_" --include="*.php" . in the project folder. You cannot estimate the size of the job without seeing how many calls sit in how many files.
  2. Back up. Both the files and the database. If you are not using version control yet, this job is a good excuse to start.
  3. Add db.php and replace the connection lines, one by one, with a require of that file.
  4. Go file by file. Simple, rarely visited pages first; critical places such as login, payment and the admin panel last. Try each page in the browser after you touch it.
  5. Run it locally on a current PHP version. Upgrade the live server only after every mysql_ call is gone.
  6. Grep again at the end. The job is not done until you see zero results. Do not forget included helper files and cron scripts.

You will find "compatibility layer" libraries online that redefine the mysql_* functions and call mysqli behind the scenes. They can be a stopgap to get a site back up in a hurry, but they add nothing in terms of security: variables are still being pasted into query text. Do not treat them as a permanent fix.

Common mistakes

  • Embedding variables in prepare. If you wrote $pdo->prepare("... WHERE id = $id") you are not using a prepared statement; you only changed the function name. Variables must always travel through execute.
  • Trying to pass table and column names as placeholders. Placeholders are for values only. If the sort column comes from the user, keep the allowed names in an array and pick from it: in_array($sort, ['title', 'created_at'], true).
  • Writing the percent sign in the query for LIKE. LIKE '%:q%' does not work. Write LIKE :q in the query and send the value as '%' . $q . '%'.
  • IN lists. You cannot hand an array to a single placeholder. Generate one question mark per element: implode(',', array_fill(0, count($ids), '?')).
  • LIMIT values. With emulation on, numbers passed through the execute array are sent as strings and LIMIT '10' fails. Either turn emulation off (the option above) or use bindValue(':limit', $limit, PDO::PARAM_INT).
  • Using the same named placeholder twice. With emulation off, :q cannot appear in two places in one query; split it into :q1 and :q2.
  • Trusting rowCount after a SELECT. Replacing mysql_num_rows with rowCount() does not give the right answer on every database. If you need the number of rows, use SELECT COUNT(*) with fetchColumn(), or count the result of fetchAll().
  • Showing the error message to visitors. Do not carry over the old or die(mysql_error()) habit. An exception message contains table names and sometimes connection details. Keep display_errors off in production, write the error to the log and show the visitor a generic message.
  • Settling for utf8. What MySQL calls utf8 cannot store four-byte characters. Use utf8mb4 for both the connection and the tables; if non-ASCII characters came out garbled during the migration, the connection charset is the first place to look.

A separate note on passwords

Most code that uses mysql_* also stores passwords with md5. Fix that while you are moving to PDO. Use password_hash($password, PASSWORD_DEFAULT) on registration and password_verify on login. Since you cannot know your existing users' passwords, you migrate at login: when a user is verified against the old md5 value, you generate the new hash from the plain password you hold at that moment and save it. The password column needs to be at least 255 characters long.

When the migration is finished you do not just have a site that runs on a new PHP version; you have a data layer that is closed to SQL injection, does not hide its errors and is easy to read. Most of the work is mechanical; the part that needs attention is not repeating old habits in the new syntax.

,,,,,,,,,,,

Share X Facebook LinkedIn WhatsApp

More from this category

Comments 0

No comments yet.

Leave a comment

Comments appear after approval.