How to change mysql to mysqli
P粉124070451
2023-07-27 23:56:06
<p>Based on the code below, which I use for regular mysql, how should I convert it to use mysqli? </p><p>Just change mysql_query($sql); to mysqli_query($sql);, is it that simple? </p><p><strong><code></code><code></code></strong></p>
<pre class="brush:php;toolbar:false;"><?PHP
//in my header file that is included on every page I have this
$DB["dbName"] = "emails";
$DB["host"] = "localhost";
$DB["user"] = "root";
$DB["pass"] = "";
$link = mysql_connect($DB['host'], $DB['user'], $DB['pass']) or die("<center>An Internal Error has Occured. Please report following error to the webmaster .<br><br>".mysql_error()."'</center>");
mysql_select_db($DB['dbName']);
// end header connection part
// function from a functions file that I run a mysql query through in any page.
function executeQuery($sql) {
$result = mysql_query($sql);
if (mysql_error()) {
$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> ;' .mysql_error();
}
die($error);
}
return $result;
}
// example query ran on any page of the site using executeQuery function
$sql='SELECT auto_id FROM friend_reg_user WHERE auto_id=' .$info['auto_id'];
$result_member=executequery($sql);
if($line_member=mysql_fetch_array($result_member)){
extract($line_member);
} else {
header("location: index.php");
exit;
}
?></pre>
<p><br /></p>
(I realize this is an old question, but it still comes up often...)
If you do replace mysql_* with mysqli_*, keep in mind that many mysqli_* functions require passing a database connection.
For example:
became:
In other words, a lot of checks are required.
First, you may want to replace each mysql_* function call with its corresponding mysqli_* function, at least if you are willing to use the procedural API - considering you already have some code based on the MySQL API, this will be Easier way since MySQL API is procedural.
To help you, the MySQLi extension function summary will undoubtedly be very helpful.
For example:
mysql_connect will be replaced by mysqli_connect.
mysql_error will be replaced with mysqli_error and/or mysqli_connect_error depending on the context.
mysql_query will be replaced with mysqli_query.
NOTE: For some functions you may need to double check the parameters: there may be some slight differences, but I would say not much: both mysql and mysqli are based on the same library ( libmysql; at least for PHP
For example:
After completing these steps, try executing the new version of your script...and check if everything is working; if not...then it's time to find the bug ;-)