Need HELP in converting MySQL to MySQLI in my PHP script? [duplicate]

I need some help in converting my script from using mysql to mysqli I have been trying for ever to do this and keep getting errors I have read articles on how to do this and still can get it to work.

Here is the original working script below.


require_once ('./mysqli_connect.php'); // Connect to the db.

if (isset($_POST['submitted'])) {

if ($dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD)) { // Make the connnection.

    if (!mysql_select_db (DB_NAME)) { // If it can't select the database.

        // Handle the error.
        trigger_error("Could not select the database!
<br />MySQL Error: " . mysql_error());

    } // End of mysql_select_db IF.

} else { // If it couldn't connect to MySQL.

    // Print a message to the user, include the footer, and kill the script.
    trigger_error("Could not connect to MySQL!
<br />MySQL Error: " . mysql_error());

} // End of $dbc IF.

// grab the tag
$tag = mysql_real_escape_string($_POST['tag']);

// see if the tag already exists and potentially what the current count is
$query = "SELECT id, count, page FROM tags WHERE tag='$tag'";
$result = mysql_query($query);

//--if there is a row, that means the tag exists
//--pull out the tag ID and the current count and increment by one.
  $tag_info = mysql_fetch_array($result);
  $tag_info_id = $tag_info["id"];
  $tag_info_count = $tag_info["count"] + 1;

//--update the table with the new count
  $sql_update_cnt = "UPDATE tags SET count='$tag_info_count' 
                            WHERE id='$tag_info_id'";

  echo "$tag now with $tag_info_count instances";
// tag is not there, so insert a new instance
  $query = "INSERT INTO tags (tag, count) VALUES ('$tag', 1)";
if (!mysql_query($query, $dbc))
  die('Error: ' . mysql_error());
echo "1 record added";

Here is the errors I keep getting.

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given on line 13

Warning: mysqli_error() expects exactly 1 parameter, 0 given on line 16
Asked By: bot

Answer #1:

It's all a matter of changing mysql to mysqli.

For example, you could call mysqli_query just like you do mysql_query here.

When you call these functions, you need to pass in the database reference as the first parameter.

See the mysqli function reference here

Answered By: bot

Answer #2:

If you're going to go through the hassle, I would really recommend you consider PDO instead.

Answered By: Jacob Relkin

Answer #3:

It's been a while since I've done a mysql->mysqli conversion (like 2 or 3 years), but IIRC there are some functions for which you also have to reverse the parameter order. Isn't that lovely?

Answered By: Jason S
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

# More Articles