How to change mysql to mysqli?

How to change mysql to mysqli?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Migrating from MySQL to MySQLi: It's Not Just a String Replacement

Changing mysql_query() to mysqli_query() is frequently suggested as a quick fix for legacy PHP code, but doing so without understanding the underlying architectural differences will result in broken applications. The old mysql_* extension was deprecated in PHP 5.5.0 and removed entirely in PHP 7.0.0. Attempting to run this exact code on a modern server environment will trigger fatal errors immediately.

The core issue isn't just renaming the function; it is how the connection object handles prepared statements and resources. In your provided snippet, you are currently using unprepared queries with direct string concatenation for values like $info['auto_id']. This approach leaves your database vulnerable to SQL injection attacks. While mysqli_query() can technically execute a raw SQL string, it does not inherently prevent injection unless you explicitly use prepared statements or escape the input data before passing it to the function.

To migrate your code safely, you must shift from procedural style (which matches your current setup) to object-oriented usage, or at least ensure strict separation of connection logic and query logic. Here is how to refactor your header file and execute function.

First, update your connection initialization in the header file. Instead of using mysql_connect, which returns a resource that cannot be easily managed in modern PHP, you should instantiate a mysqli object directly. This allows for better error handling and explicit configuration options like character sets.

// In your header file
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "emails";

try {
    $DB['link'] = new mysqli($host, $user, $pass, $dbName);
    
    // Check connection
    if ($DB['link']->connect_error) {
        die("Connection failed: " . $DB['link']->connect_error);
    }
} catch (Exception $e) {
    die("An Internal Error has Occured. Please report following error to the webmaster.");
}

Next, you need to modify your executeQuery function. The procedural mysqli_query() signature requires passing the connection object as the first argument. Furthermore, because your original code lacks protection against SQL injection, you should refactor the function to accept a prepared statement pattern or strictly sanitize inputs if you must stick to raw queries (though prepared statements are strongly recommended).

Here is a robust version of your function that utilizes prepared statements:

function executeQuery($connection, $sqlTemplate, $params = []) {
    // Prepare the statement
    $stmt = $connection->prepare($sqlTemplate);
    
    // Bind parameters if provided (e.g., 'i' for integer)
    if (!empty($params)) {
        $types = str_repeat('i', count($params)); // Assuming integers for auto_id
        $stmt->bind_param($types, ...$params);
    }

    // Execute and handle errors
    if (!$stmt->execute()) {
        $error = '<br><center><font size="+1" face="arial" color="red">An Internal Error has Occured.<BR> The error has been recorded for review</font></center><br>';
        
        if ($_SESSION['auto_id'] == 1) {
            // Debugging logic retained from original but safely displayed
            $sql_formatted = highlight_string(stripslashes($connection->last_error), true); 
            $error .= '<b>The MySQL Error Returned</b><br>' . $stmt->error;
        }
        
        die($error);
    }

    // For SELECT queries, fetch the result set
    if ($stmt instanceof mysqli_result) {
        return $stmt->get_result();
    } else {
        return true; // Affected rows for INSERT/UPDATE/DELETE
    }
}

Finally, update your usage logic. In your original code, you concatenate $info['auto_id'] directly into the SQL string:

$sql='SELECT auto_id FROM friend_reg_user WHERE auto_id=' .$info['auto_id'];

This must change to a template with placeholders:

$infoId = $info['auto_id']; // Ensure this value is validated or trusted
$sql = 'SELECT auto_id FROM friend_reg_user WHERE auto_id=?';
$result_member = executeQuery($DB['link'], $sql, [$infoId]);

By switching to mysqli, you gain access to features like multi-statement support and improved error reporting. However, the most significant benefit is security. If you are looking for a more comprehensive solution that abstracts these database interactions further, frameworks like Laravel provide built-in query builders that handle connection pooling and prepared statements automatically. You can explore resources at https://laravelcompany.com to see how modern application architectures solve these legacy issues without requiring manual migration of every single file.

Our network