How to change mysql to mysqli?
Asked Answered
P

12

82

Based on this code below I use for regular mysql, how could I convert it to use mysqli?

Is it as simple as changing mysql_query($sql); to mysqli_query($sql);?

<?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 anypage 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;
}
?>
Pollie answered 7/9, 2009 at 18:56 Comment(0)
R
87

The first thing to do would probably be to replace every mysql_* function call with its equivalent mysqli_*, at least if you are willing to use the procedural API -- which would be the easier way, considering you already have some code based on the MySQL API, which is a procedural one.

To help with that, the MySQLi Extension Function Summary is definitely something that will prove helpful.

For instance:

Note: For some functions, you may need to check the parameters carefully: Maybe there are some differences here and there -- but not that many, I'd say: both mysql and mysqli are based on the same library (libmysql ; at least for PHP <= 5.2)

For instance:

  • with mysql, you have to use the mysql_select_db once connected, to indicate on which database you want to do your queries
  • mysqli, on the other side, allows you to specify that database name as the fourth parameter to mysqli_connect.
  • Still, there is also a mysqli_select_db function that you can use, if you prefer.

Once you are done with that, try to execute the new version of your script... And check if everything works ; if not... Time for bug hunting ;-)
Recognizance answered 7/9, 2009 at 19:4 Comment(11)
As long as you want to keep procedural code, switching from mysql to mysqli should not be too hard ; but, if your codebase is not too big (ie, going from one API to the other wouldn't mean too much work), you might want to use an object-oriented API ; it'll require more work, though... And if going for a total rewrite to an OO-API, I'd go with PDO instead of mysqli...Recognizance
I mean reading up on the 2 all day now, from what I understand isn't the main difference with PDO, that PDO allows you to use a differnt DB system. IF that is the only benefit then it would not be much help in my case as I will never need a different one for this application.Pollie
In this case, mysqli will probably be just fine :-) especially as you already have some code built on mysql.Recognizance
There are tools to automate the migration process, like: github.com/philip/MySQLConverterToolPhebe
Note that some mysqli_* procedural functions have first two parameters switched. Old style was mysql_*(q, link, ...) and new style is mysqli_*(link, q, ...).Witted
There's a very good and more detailed article on doing this conversion (2015+) at phpclasses.org/blog/package/9199/post/…Caladium
Although this is the accepted answer, and answers the question, it does not mention the fact that such a conversion would still leave you open to serious SQLi security vulnerabilities (due to the lack of prepared statements). I'd recommend referring to the official PHP documentation for using prepared statements in PHP in that regard.Triphylite
worth mentioning mysqli_num_rowsLesh
@Stnfordly not at all. There is no point in listing all mysqli functions in this list. It shows a pattern. You are supposed to pick it up and extrapolate to other function names. Not to mention that this particular function is outright uselessGearard
My comment did not ask your opinion - it gave mine - my opinion does not require your condoning.Lesh
Everybody saying "ya, but PDO is the way to go" needs to understand that a system can have literally thousands of references to mysql_ so upgrading to PDO is not a trivial thing and so there are legit reasons for wanting to switch to mysqli_Tice
I
38

(I realise this is old, but it still comes up...)

If you do replace mysql_* with mysqli_* then bear in mind that a whole load of mysqli_* functions need the database link to be passed.

E.g.:

mysql_query($query)

becomes

mysqli_query($link, $query)

I.e., lots of checking required.

Inflatable answered 8/5, 2015 at 17:57 Comment(1)
For Future Readers: Do not stop reading until you see Dharmans answer from July 2019, below. THAT should be the accepted answer for this question, imho.Aachen
M
33

The ultimate guide to upgrading mysql_* functions to MySQLi API

The reason for the new mysqli extension was to take advantage of new features found in MySQL systems versions 4.1.3 and newer. When changing your existing code from mysql_* to mysqli API you should avail of these improvements, otherwise your upgrade efforts could go in vain.
The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:

  • Object-oriented interface
  • Support for Prepared Statements
  • Enhanced debugging capabilities

When upgrading from mysql_* functions to MySQLi, it is important to take these features into consideration, as well as some changes in the way this API should be used.

1. Object-oriented interface versus procedural functions.

The new mysqli object-oriented interface is a big improvement over the older functions and it can make your code cleaner and less susceptible to typographical errors. There is also the procedural version of this API, but its use is discouraged as it leads to less readable code, which is more prone to errors.

To open new connection to the database with MySQLi you need to create new instance of MySQLi class.

$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

Using procedural style it would look like this:

$mysqli = mysqli_connect($host, $user, $password, $dbName);
mysqli_set_charset($mysqli, 'utf8mb4');

Keep in mind that only the first 3 parameters are the same as in mysql_connect. The same code in the old API would be:

$link = mysql_connect($host, $user, $password);
mysql_select_db($dbName, $link);
mysql_query('SET NAMES utf8');

If your PHP code relied on implicit connection with default parameters defined in php.ini, you now have to open the MySQLi connection passing the parameters in your code, and then provide the connection link to all procedural functions or use the OOP style.

For more information see the article: How to connect properly using mysqli

2. Support for Prepared Statements

This is a big one. MySQL has added support for native prepared statements in MySQL 4.1 (2004). Prepared statements are the best way to prevent SQL injection. It was only logical that support for native prepared statements was added to PHP. Prepared statements should be used whenever data needs to be passed along with the SQL statement (i.e. WHERE, INSERT or UPDATE are the usual use cases).

The old MySQL API had a function to escape the strings used in SQL called mysql_real_escape_string, but it was never intended for protection against SQL injections and naturally shouldn't be used for the purpose.
The new MySQLi API offers a substitute function mysqli_real_escape_string for backwards compatibility, which suffers from the same problems as the old one and therefore should not be used unless prepared statements are not available.

The old mysql_* way:

$login = mysql_real_escape_string($_POST['login']);
$result = mysql_query("SELECT * FROM users WHERE user='$login'");

The prepared statement way:

$stmt = $mysqli->prepare('SELECT * FROM users WHERE user=?');
$stmt->bind_param('s', $_POST['login']);
$stmt->execute();
$result = $stmt->get_result();

Prepared statements in MySQLi can look a little off-putting to beginners. If you are starting a new project then deciding to use the more powerful and simpler PDO API might be a good idea.

3. Enhanced debugging capabilities

Some old-school PHP developers are used to checking for SQL errors manually and displaying them directly in the browser as means of debugging. However, such practice turned out to be not only cumbersome, but also a security risk. Thankfully MySQLi has improved error reporting capabilities.

MySQLi is able to report any errors it encounters as PHP exceptions. PHP exceptions will bubble up in the script and if unhandled will terminate it instantly, which means that no statement after the erroneous one will ever be executed. The exception will trigger PHP Fatal error and will behave as any error triggered from PHP core obeying the display_errors and log_errors settings. To enable MySQLi exceptions use the line mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT) and insert it right before you open the DB connection.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

If you were used to writing code such as:

$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

or

$result = mysql_query('SELECT * WHERE 1=1') or die(mysql_error());

you no longer need to die() in your code.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli($host, $user, $password, $dbName);
$mysqli->set_charset('utf8mb4');

$result = $mysqli->query('SELECT * FROM non_existent_table');
// The following line will never be executed due to the mysqli_sql_exception being thrown above
foreach ($result as $row) {
    // ...
}

If for some reason you can't use exceptions, MySQLi has equivalent functions for error retrieval. You can use mysqli_connect_error() to check for connection errors and mysqli_error($mysqli) for any other errors. Pay attention to the mandatory argument in mysqli_error($mysqli) or alternatively stick to OOP style and use $mysqli->error.

$result = $mysqli->query('SELECT * FROM non_existent_table') or trigger_error($mysqli->error, E_USER_ERROR);

See these posts for more explanation:
mysqli or die, does it have to die?
How to get MySQLi error information in different environments?

4. Other changes

Unfortunately not every function from mysql_* has its counterpart in MySQLi only with an "i" added in the name and connection link as first parameter. Here is a list of some of them:

  • mysql_client_encoding() has been replaced by mysqli_character_set_name($mysqli)
  • mysql_create_db has no counterpart. Use prepared statements or mysqli_query instead
  • mysql_drop_db has no counterpart. Use prepared statements or mysqli_query instead
  • mysql_db_name & mysql_list_dbs support has been dropped in favour of SQL's SHOW DATABASES
  • mysql_list_tables support has been dropped in favour of SQL's SHOW TABLES FROM dbname
  • mysql_list_fields support has been dropped in favour of SQL's SHOW COLUMNS FROM sometable
  • mysql_db_query -> use mysqli_select_db() then the query or specify the DB name in the query
  • mysql_fetch_field($result, 5) -> the second parameter (offset) is not present in mysqli_fetch_field. You can use mysqli_fetch_field_direct keeping in mind the different results returned
  • mysql_field_flags, mysql_field_len, mysql_field_name, mysql_field_table & mysql_field_type -> has been replaced with mysqli_fetch_field_direct
  • mysql_list_processes has been removed. If you need thread ID use mysqli_thread_id
  • mysql_pconnect has been replaced with mysqli_connect() with p: host prefix
  • mysql_result -> use mysqli_data_seek() in conjunction with mysqli_field_seek() and mysqli_fetch_field()
  • mysql_tablename support has been dropped in favour of SQL's SHOW TABLES
  • mysql_unbuffered_query has been removed. See this article for more information Buffered and Unbuffered queries
Martyrize answered 11/7, 2019 at 22:6 Comment(3)
The answer is a good surprise as for this kind of question you are expecting rather a useless out-of-the-loop remark. I believe it will get the due recognition. just a couple nitpicks. There is mysql_set_charset() as well, just a factcheck; Iwouldn't blame mres() for being "insufficient to prevent SQL injections". You cannot blame a hatchet for not sawing your logs. So I would rather put it as "it was never intended for protection and naturally shouldn't be used for the purpose"Gearard
@YourCommonSense Thanks, I have changed the wording. In regards to mysql_set_charset it was not available with MySQL < 5.0.7. I wanted to point out the difference in how things were done back then vs now, rather than being 1 to 1 replacement.Martyrize
Brilliant answer - and not nearly enough upvoted. I'm going to check out your other answers and see what else you've done that is brilliant and upvoteable. Your time and effort on this question is much appreciated.Aachen
D
24

The easiest way i always handle this Where

 $con = mysqli_connect($serverName,$dbusername,$dbpassword);

3 steps replacement in the following order

  1. All "mysql_select_db(" with "mysqli_select_db($con,"
  2. All "mysql_query(" with "mysqli_query($con," and
  3. All "mysql_" with "mysqli_".

This works for me everytime

Dr answered 20/5, 2017 at 2:47 Comment(4)
I'd add searching for all function strings and placing a global $con; on top of the function's content, as $con defined outside of the function will not be available by default due to the variable's scope in PHP.Gyrate
Not a perfect answer — some functions still need to add the $con parameter (e.g. mysqi_affected_rows, mysqi_real_escape_string) — but helpful because it sums up the sort of changes needed.Lame
Also don't forget mysql_error() gets changed to mysqli_error($con)Phlogopite
If there were any files included in source who were named "mysql_.....php" , they will become "mysqli_.....php". Be careful.Stichter
E
21

2020+ Answer

I've created a tool called Rector, that handles instant upgrades. There is also mysql → mysqli set.

It handles:

  • function renaming

  • constant renaming

  • switched arguments

  • non-1:1 function calls changes, e.g.

      $data = mysql_db_name($result, $row);
    

      mysqli_data_seek($result, $row);
      $fetch = mysql_fetch_row($result);
      $data = $fetch[0];
    

How to use Rector?

1. Install it via Composer

composer require rector/rector --dev

2. Create rector.php in project root directory with the Mysql to Mysqli set

<?php

use Rector\Set\ValueObject\SetList;
use Rector\Config\RectorConfig;

return static function (RectorConfig $rectorConfig): void {
    $rectorConfig->sets([
        SetList::MYSQL_TO_MYSQLI,
    ]);
};

3. Let Rector run on e.g. /src directory to only show the diffs

vendor/bin/rector process src --dry-run

4. Let Rector change the code

vendor/bin/rector process src

I've already run it on 2 big PHP projects and it works perfectly.

Ensample answered 4/5, 2020 at 17:18 Comment(14)
Does it enable mysqli error reporting and does it make the switch to prepared statements with parameter binding?Martyrize
I don't understand how this works or why this answer has 8 upvotes. Even the example you showed still contains broken code. mysql_fetch_row does not exist and your tool doesn't create such shim. In fact, I tried a few examples and it doesn't fix anything and only introduces more problems. Missing arguments, nonexistent functions, sometimes it works sometimes it doesn't change anything. Good idea but it is far from being the solution. And most importantly it doesn't seem to make the switch to parameterized prepared statements, which was the reason for mysqli to exist in the first place.Martyrize
Rector works based on abstract syntax tree (AST) based on nikic/php-parser. It looks for a patterns in the code and replaces them with defined code. If there are missed edge-cases, we need to cover them by adding a new sub-rule. Could make an issue there with before/after snippets of what is misisng?Ensample
One obvious issue is in the answer you have written. mysql_fetch_row does not exist anymore and when it did it was not compatible with mysqli. Stick with OOP style and you will avoid such mistakes.Martyrize
I'm unable to fix Rector rule here, as I need full before/after diff to understand needed change.Ensample
I have explained the situation in detail and provided some code examples on GitHub. You can execute your rector rule on them and see that it doesn't make the necessary changes. At least I did as described in this answer and it only created broken code.Martyrize
That's awesome! Thank you. I've create an issue in Rector to handle this: github.com/rectorphp/rector/issues/3315Ensample
Hi Tomas, I have used the mysql-to-mysqli set as you recommended, however it does not include the right DB $link variable in any case. It seems to just randomly insert the nearest variable it finds, so every mysqli_query() function fails. Is there a way to improve which link variable it uses for this? It seems to work after manually fixing every single instance, but when we're talking about many thousands of files, it's impossible.Manion
Report it on Github issues: github.com/rectorphp/rector, so we can fix itEnsample
currently above composer installs 0.8.56 of rector, and i get The "--set" option does not exist.Crigger
Hi @Crigger - thanks for reporting. This option is no more used, so I've updated the example with rector.php config instead. It prevents typoes and is easier to configure. Let me know how it works for youEnsample
If i remember right, i have read myself trough docs, and assembled rector.php as suggested. Had to search the net for examples, but at last i was able to creat a single-set config fix mysql2mysqli in the project in question. $parameters->set(Option::SETS, [SetList::MYSQL_TO_MYSQLI]);Crigger
With a few minor changes, this worked great. First, run this from your source directory, not the PHP executable dir. Second, specify the full path to the rector dir. Third, the php specified here is missing a line. Define $parameters before you use it, $parameters = $containerConfigurator->parameters();Ceram
Currently, there is no such set MYSQL_TO_MYSQLI in rector 1.0 –Mors
P
8

In case of big projects, many files to change and also if the previous project version of PHP was 5.6 and the new one is 7.1, you can create a new file sql.php and include it in the header or somewhere you use it all the time and needs sql connection. For example:

//local
$sql_host =     "localhost";      
$sql_username = "root";    
$sql_password = "";       
$sql_database = "db"; 


$mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

// /* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
} else {
    // printf("Current character set: %s\n", $mysqli->character_set_name());
}
if (!function_exists('mysql_real_escape_string')) {
    function mysql_real_escape_string($string){
        global $mysqli;
        if($string){
            // $mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );            
            $newString =  $mysqli->real_escape_string($string);
            return $newString;
        }
    }
}
// $mysqli->close();
$conn = null;
if (!function_exists('mysql_query')) {
    function mysql_query($query) {
        global $mysqli;
        // echo "DAAAAA";
        if($query) {
            $result = $mysqli->query($query);
            return $result;
        }
    }
}
else {
    $conn=mysql_connect($sql_host,$sql_username, $sql_password);
    mysql_set_charset("utf8", $conn);
    mysql_select_db($sql_database);
}

if (!function_exists('mysql_fetch_array')) {
    function mysql_fetch_array($result){
        if($result){
            $row =  $result->fetch_assoc();
            return $row;
        }
    }
}

if (!function_exists('mysql_num_rows')) {
    function mysql_num_rows($result){
        if($result){
            $row_cnt = $result->num_rows;;
            return $row_cnt;
        }
    }
}

if (!function_exists('mysql_free_result')) {
    function mysql_free_result($result){
        if($result){
            global $mysqli;
            $result->free();

        }
    }
}

if (!function_exists('mysql_data_seek')) {
    function mysql_data_seek($result, $offset){
        if($result){
            global $mysqli;
            return $result->data_seek($offset);

        }
    }
}

if (!function_exists('mysql_close')) {
    function mysql_close(){
        global $mysqli;
        return $mysqli->close();
    }
}

if (!function_exists('mysql_insert_id')) {
    function mysql_insert_id(){
            global $mysqli;
            $lastInsertId = $mysqli->insert_id;
            return $lastInsertId;
    }
}

if (!function_exists('mysql_error')) {
    function mysql_error(){
        global $mysqli;
        $error = $mysqli->error;
        return $error;
    }
}
Priapitis answered 13/12, 2017 at 13:53 Comment(2)
and how should I use this to test with mysqli functions?? For example Your file checks first if mysql_query exits if so use for 5.6 but how do test if mysqli_query works?Binaural
and use it: <pre> $id_cat = (int)'4'; $sql = "DELETE FROM categories WHERE id='$id_cat' OR parent_id ='$id_cat'"; mysql_query($sql) or die('Error SQL !<br />'.$sql.'<br />'.mysql_error()); </pre>Priapitis
T
6

I would tentatively recommend using PDO for your SQL access.

Then it is only a case of changing the driver and ensuring the SQL works on the new backend. In theory. Data migration is a different issue.

Abstract database access is great.

Torch answered 7/9, 2009 at 18:59 Comment(0)
E
4

Here is a complete tutorial how to make it quickly if you need to make worgking again a website after PHP upgrade. I used it after upgrading hosting for my customers from 5.4 (OMG!!!) to 7.x PHP version.

This is a workaround and it is better to rewrite all code using PDO or mysqli Class.

1. Connection definition

First of all, you need to put the connection to a new variable $link or $con, or whatever you want.

Example

Change the connection from :

@mysql_connect($host, $username, $password) or die("Error message...");
@mysql_select_db($db);

or

@mysql_connect($host, $username, $password, $db) or die("Error message...");

to:

$con = mysqli_connect($host, $username, $password, $db) or die("Error message...");

2. mysql_* modification

With Notepad++ I use "Find in files" (Ctrl + Shift + f) :

Search and replace notepad++ box

in the following order I choose "Replace in Files" :

  1. mysql_query( -> mysqli_query($con,

  2. mysql_error() -> mysqli_error($con)

  3. mysql_close() -> mysqli_close($con)

  4. mysql_insert_id() -> mysqli_insert_id($con)

  5. mysql_real_escape_string( -> mysqli_real_escape_string($con,

  6. mysql_ -> mysqli_

3. adjustments

if you get errors it is maybe because your $con is not accessible from your functions.

You need to add a global $con; in all your functions, for example :

function my_function(...) {
    global $con;
    ...
}

In SQL class, you will put connection to $this->con instead of $con. and replace it in each functions call (for example : mysqli_query($con, $query);)

Electroanalysis answered 10/4, 2018 at 10:8 Comment(4)
These APIs are so different from each other you can't upgrade with a search and replace. There have been changes in functionality and in the way you use it. If you only do search and replace you are missing the point of the removal of mysql_* APIMartyrize
This is not THE solution, but when you inherit a website and have no time to rewrite all the code, this is a workaround @Martyrize and it's working,Electroanalysis
Gotta add a few other commands that need modification, which I found out the hard way... mysql_insert_id() becomes mysqli_insert_id($con) and mysql_real_escape_string($var) becomes mysqli_real_escape_string($con, $var); otherwise they don't work...Chordophone
Thanks @LaurensSwart I just added it to mysql_* modification procedure.Electroanalysis
H
3

If you have a lot files to change in your projects you can create functions with the same names like mysql functions, and in the functions make the convert like this code:

$sql_host =     "your host";      
$sql_username = "username";    
$sql_password = "password";       
$sql_database = "database";       



$mysqli = new mysqli($sql_host , $sql_username , $sql_password , $sql_database );


/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}


function mysql_query($query){
    $result = $mysqli->query($query);
    return $result;

}

function mysql_fetch_array($result){
    if($result){
        $row =  $result->fetch_assoc();
         return $row;
       }
}

function mysql_num_rows($result){
    if($result){
         $row_cnt = $result->num_rows;;
         return $row_cnt;
       }
}
Hypochondriac answered 23/5, 2017 at 11:39 Comment(0)
W
3

Although this topic is a decade old, I still often require to 'backpatch' existing applications which relied upon the mysql extension — the original programmers were too lazy to refactor all their code, and just tell customers to make sure that they run the latest PHP 5.6 version available.

PHP 5.6 is now officially deprecated; in other words, developers had a decade to get rid of their dependencies upon mysql and move to PDO (or, well, mysqli...). But... changing so much legacy code is expensive, and not every manager is willing to pay for the uncountable hours to 'fix' projects with dozens of thousands of lines.

I've searched for many solutions, and, in my case, I often used the solution presented by @esty-shlomovitz — but in the meantime, I've found something even better:

https://www.phpclasses.org/package/9199-PHP-Replace-mysql-functions-using-the-mysqli-extension.html

(you need to register to download it, but that just takes a minute)

These are just two files which act as drop-in replacements for the whole mysql extension and very cleverly emulate pretty much everything (using mysqli) without the need to worry much about it. Of course, it's not a perfect solution, but very likely it will work in 99% of all cases out there.

Also, a good tutorial for dealing with the chores of migration (listing many of the common pitfalls when migrating) can also be found here: https://www.phpclasses.org/blog/package/9199/post/3-Smoothly-Migrate-your-PHP-Code-using-the-Old-MySQL-extension-to-MySQLi.html

(if you're reading this in 2030 and the PHPclasses website is down, well, you can always try archive.org :-)

Update: @crashwap noted on the comments below that you can also get the same code directly from GitHub. Thanks for the tip, @crashwap :-)

Wilburnwilburt answered 24/9, 2019 at 16:57 Comment(2)
To save trouble with phpclasses.org registration/login system (basically doesn't work unless you provide facebook/github/SO/etc auth), I also found the exact same code available here (note that you need both files: the .class.php and the .func.php - the .class file will include() the .func file).Checky
@Checky thanks! I've changed my answer to add your tip. Nice googling, BTW — much better than mine lolWilburnwilburt
B
3

I have just created the function with the same names to convert and overwrite to the new one php7:

$host =     "your host";      
$un = "username";    
$pw = "password";       
$db = "database"; 

$MYSQLI_CONNECT = mysqli_connect($host, $un, $pw, $db);

function mysql_query($q) {
    global $MYSQLI_CONNECT;
    return mysqli_query($MYSQLI_CONNECT,$q);
}

function mysql_fetch_assoc($q) {
    return mysqli_fetch_assoc($q);
}

function mysql_fetch_array($q){
    return mysqli_fetch_array($q , MYSQLI_BOTH);
}

function mysql_num_rows($q){
    return mysqli_num_rows($q);
}

function mysql_insert_id() {
    global $MYSQLI_CONNECT;
    return mysqli_insert_id($MYSQLI_CONNECT);
}

function mysql_real_escape_string($q) {
    global $MYSQLI_CONNECT;
    return mysqli_real_escape_string($MYSQLI_CONNECT,$q);
}

It works for me , I hope it will work for you all , if I mistaken , correct me.

Babcock answered 25/10, 2019 at 17:47 Comment(0)
S
-2

similar to dhw's answer but you don't have to worry about setting the link as global in all the function because that is kind of difficult:

just use this code in your config file:

$sv_connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$db_connection = mysqli_select_db ($sv_connection, $dbname);
mysqli_set_charset($sv_connection, 'utf8'); //optional

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit();
}


function mysqljx_query($q){
    global $sv_connection;
    return mysqli_query($sv_connection, $q);
}

function mysqljx_fetch_array($r){
    return mysqli_fetch_array($r);
}

function mysqljx_fetch_assoc($r){
    return mysqli_fetch_assoc($r);
}

function mysqljx_num_rows($r){
    return mysqli_num_rows($r);
}

function mysqljx_insert_id(){
    global $sv_connection;
    return mysqli_insert_id($sv_connection);
}

function mysqljx_real_escape_string($string){
    global $sv_connection;
    return mysqli_real_escape_string($sv_connection, $string);
}

-now do a search for php files that contain "mysql_" (i used total commander for that - Alt+F7, search for "*.php", find text "mysql_", Start search, Feed to listbox)

-drag&drop them all in Notepad++, there u press CTRL+H, Find what: "mysql_", Replace with "mysqljx_", "Replace All in All Opened Documents"

if you are worried that you have other functions than the ones listed above just replace one by one ("mysql_query" with "mysqljx_query", then mysql_fetch_array with "mysqljx_fetch_array" etc..) and then search again for "mysql_" and if its still there its a uncovered function and you can just add it same as the rest..

that is it

Stacystadholder answered 13/2, 2021 at 22:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.