Converting MySQL Code to MySQLi

Converting MySQL Code to MySQLi
Migrating from the deprecated MySQL extension to MySQLi (MySQL Improved) is an essential step for PHP developers. The MySQL extension is no longer supported in PHP, which makes transitioning to MySQLi critical for maintaining the security, performance, and future-proofing of your applications.

MySQLi offers enhanced features, including support for prepared statements, object-oriented programming, and improved error handling. This article provides a comprehensive guide to converting your existing MySQL code to MySQLi, with step-by-step instructions and code examples.

Understanding the Need for Migration

Before diving into the migration process, it’s important to understand why converting from MySQL to MySQLi is necessary. The MySQL extension is outdated and lacks many modern features that MySQLi provides. Without migration:

  • Your code may become insecure, particularly vulnerable to SQL injection attacks.
  • You won’t be able to take advantage of MySQLi’s advanced features, like prepared statements, which help improve security and performance.
  • Future PHP versions will not support the MySQL extension, making your application incompatible with newer PHP versions.

Overview of Key Differences Between MySQL and MySQLi

Before converting your code, it’s helpful to understand the key differences between the MySQL extension and MySQLi:

  • Object-Oriented Support: MySQLi supports both procedural and object-oriented programming, whereas MySQL is strictly procedural.
  • Prepared Statements: MySQLi allows the use of prepared statements, which help prevent SQL injection.
  • Improved Error Handling: MySQLi provides more detailed error messages and better error handling mechanisms.
  • Transactions and Multiple Statements: MySQLi supports transactions and executing multiple SQL statements in a single query.

Step-by-Step Migration Process

Step 1: Replace MySQL Functions with MySQLi Functions

The first step in converting your code is replacing MySQL functions with their MySQLi equivalents. MySQLi offers both procedural and object-oriented interfaces, so you can choose the style that best fits your coding practices.

Example: Connecting to the Database

Old MySQL Code:

				
					<?php
$link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('database_name', $link);
?>

				
			
Converted MySQLi Code (Procedural):
				
					<?php
$link = mysqli_connect('localhost', 'username', 'password', 'database_name');
if (!$link) {
    die('Could not connect: ' . mysqli_connect_error());
}
?>

				
			
Converted MySQLi Code (Object-Oriented):
				
					<?php
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
?>

				
			

Step 2: Replace MySQL Query Functions

Once the connection code is converted, replace MySQL query functions with MySQLi functions. This includes functions like mysql_query, mysql_fetch_array, mysql_fetch_assoc, etc.

Example: Executing a Query and Fetching Results

Old MySQL Code:

				
					<?php
$result = mysql_query("SELECT id, username FROM users");
while ($row = mysql_fetch_assoc($result)) {
    echo $row['id'] . " - " . $row['username'] . "<br>";
}
?>

				
			
Converted MySQLi Code (Procedural):
				
					<?php
$result = mysqli_query($link, "SELECT id, username FROM users");
while ($row = mysqli_fetch_assoc($result)) {
    echo $row['id'] . " - " . $row['username'] . "<br>";
}
?>

				
			

Converted MySQLi Code (Object-Oriented):

				
					<?php
$result = $mysqli->query("SELECT id, username FROM users");
while ($row = $result->fetch_assoc()) {
    echo $row['id'] . " - " . $row['username'] . "<br>";
}
?>

				
			

Step 3: Handle Error Reporting

MySQLi provides more detailed error messages than MySQL, which helps in debugging. Replace mysql_error with mysqli_error for procedural code or ->error for object-oriented code.

Example: Handling Errors

Old MySQL Code:

				
					<?php
if (!mysql_query("INSERT INTO users (username) VALUES ('test_user')")) {
    echo "Error: " . mysql_error();
}
?>

				
			

Converted MySQLi Code (Procedural):

				
					<?php
if (!mysqli_query($link, "INSERT INTO users (username) VALUES ('test_user')")) {
    echo "Error: " . mysqli_error($link);
}
?>

				
			

Converted MySQLi Code (Object-Oriented):

				
					<?php
if (!$mysqli->query("INSERT INTO users (username) VALUES ('test_user')")) {
    echo "Error: " . $mysqli->error;
}
?>

				
			

Step 4: Implement Prepared Statements

Prepared statements are one of the most significant improvements in MySQLi. They help prevent SQL injection and improve performance by allowing the database to parse queries only once.

Example: Using Prepared Statements

Old MySQL Code:

				
					<?php
$username = mysql_real_escape_string($_POST['username']);
mysql_query("INSERT INTO users (username) VALUES ('$username')");
?>

				
			

Converted MySQLi Code (Procedural):

				
					<?php
$stmt = mysqli_prepare($link, "INSERT INTO users (username) VALUES (?)");
mysqli_stmt_bind_param($stmt, 's', $_POST['username']);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
?>

				
			

Converted MySQLi Code (Object-Oriented):

				
					<?php
$stmt = $mysqli->prepare("INSERT INTO users (username) VALUES (?)");
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->close();
?>

				
			

Step 5: Migrate Transactions and Multiple Statements

If your code uses transactions or requires executing multiple statements in a single call, MySQLi offers robust support for these features.

Example: Using Transactions

Old MySQL Code:

MySQL extension does not support transactions.

Converted MySQLi Code (Object-Oriented):

				
					<?php
$mysqli->begin_transaction();

try {
    $mysqli->query("INSERT INTO users (username) VALUES ('user1')");
    $mysqli->query("UPDATE users SET email='updated@example.com' WHERE username='user1'");
    $mysqli->commit();
} catch (Exception $e) {
    $mysqli->rollback();
    echo "Failed: " . $e->getMessage();
}
?>

				
			

Step 6: Update Fetching and Displaying Data

In MySQLi, fetching and displaying data requires a few adjustments depending on whether you’re using the procedural or object-oriented approach.

Example: Fetching and Displaying Data

Old MySQL Code:

				
					<?php
$result = mysql_query("SELECT id, username FROM users");
while ($row = mysql_fetch_array($result)) {
    echo $row['id'] . " - " . $row['username'] . "<br>";
}
?>

				
			

Converted MySQLi Code (Procedural):

				
					<?php
$result = mysqli_query($link, "SELECT id, username FROM users");
while ($row = mysqli_fetch_array($result)) {
    echo $row['id'] . " - " . $row['username'] . "<br>";
}
?>

				
			

Converted MySQLi Code (Object-Oriented):

				
					<?php
$result = $mysqli->query("SELECT id, username FROM users");
while ($row = $result->fetch_array()) {
    echo $row['id'] . " - " . $row['username'] . "<br>";
}
?>

				
			

Step 7: Close Database Connections

Finally, ensure that you close any open database connections to free up resources.

Example: Closing Connections

Old MySQL Code:

				
					<?php
mysql_close($link);
?>

				
			

Converted MySQLi Code (Procedural):

				
					<?php
mysqli_close($link);
?>

				
			

Converted MySQLi Code (Object-Oriented):

				
					<?php
$mysqli->close();
?>

				
			

Converted MySQLi Code (Object-Oriented):

				
					<?php
$mysqli->close();
?>

				
			

Testing the Migration

After completing the migration, thoroughly test your application to ensure everything works as expected. Pay special attention to:

  • Query Results: Verify that all queries return the expected results.
  • Error Handling: Ensure that error messages are clear and helpful.
  • Security: Check that security measures, like prepared statements, are properly implemented.
  • Performance: Monitor performance to ensure that the migration has not introduced any inefficiencies.

Conclusion

Migrating from the MySQL extension to MySQLi is crucial for maintaining the security, performance, and compatibility of your PHP applications. MySQLi offers significant improvements over the old MySQL extension, including support for prepared statements, object-oriented programming, and better error handling. By following the step-by-step migration process outlined in this article, you can efficiently convert your existing MySQL code to MySQLi, ensuring your application remains robust and future-proof.

Summary of Migration Steps:

  1. Replace MySQL Functions: Convert MySQL functions to MySQLi equivalents.
  2. Handle Error Reporting: Update error handling mechanisms.
  3. Implement Prepared Statements: Use prepared statements for secure queries.
  4. Migrate Transactions: Implement transactions using MySQLi.
  5. Update Fetching and Displaying Data: Adjust data fetching and display code.
  6. Close Connections: Ensure that database connections are properly closed.

Migrating to MySQLi is a worthwhile investment, providing a more secure, efficient, and scalable solution for interacting with MySQL databases in PHP.

Scroll to Top