Converting MySQL to MySQLi
Based on the provided code, it may initially seem as simple as replacing mysql_query($sql); with mysqli_query($sql);. However, for a complete conversion to MySQLi, further modifications are necessary.
Function Replacements:
The first step is to replace each mysql_* function with its corresponding mysqli_* counterpart. The MySQLi Extension Function Summary provides a comprehensive listing for this purpose.
Database Selection:
Unlike MySQL, MySQLi allows you to specify the database when connecting using the fourth parameter to mysqli_connect. Alternatively, you can still use the mysqli_select_db function if preferred.
Additional Considerations:
Example:
Here's the provided code converted to MySQLi:
// Header file with the database configuration $DB['dbName'] = "emails"; $DB['host'] = "localhost"; $DB['user'] = "root"; $DB['pass'] = ""; // Establish a connection to the database $link = mysqli_connect($DB['host'], $DB['user'], $DB['pass'], $DB['dbName']); // Query execution function function executeQuery($sql) { $result = mysqli_query($link, $sql); if (mysqli_error($link)) { $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) { $sql_formatted = highlight_string(stripslashes($sql), true); $error .= '<b>The MySQL Syntax Used</b><br>' . $sql_formatted . '<br><br><b>The MySQL Error Returned</b><br>' . mysqli_error($link); } die($error); } return $result; } // Example query $sql = 'SELECT auto_id FROM friend_reg_user WHERE auto_id=' . $info['auto_id']; $result_member = executeQuery($sql); if ($line_member = mysqli_fetch_array($result_member)) { extract($line_member); } else { header("location: index.php"); exit; } ?>
Once the conversion is complete, test your script to ensure everything is functioning correctly.
The above is the detailed content of How to Effectively Migrate from MySQL to MySQLi?. For more information, please follow other related articles on the PHP Chinese website!