Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP changing to mysqli. Is the mysqli_connection not global?

I have just started a new PHP project and I was thinking it's time to follow php suggestion and stop using mysql and swith to mysqli instead. But this gave me a problem.

Normaly my setup is like this

Index.php file and inside this file I have a 2 require statements. One that calls for the db.php file and one other to call a functions.php file. So far so good.

In the functions.php file a have a lot of different functions that is used all over the homepage and many of these are using SQL. With php old mysql API this was no problem but it seams that the new mysqli api don't allow connections to be used from included files???

For example in my db.php I have the connect statement. $db = mysql_connect(*******); And in my function.php I have mysql_query(******) and it works perfect.

But if I change the db.php to $db = mysqli_connect(*****); Then in my function.php file I can't call the mysqli_query(***). (I have also tested object oriented but it gives me the same problem).

So how to get around this problem? Is php expecting me to put the mysqli_connect statement in the beginning of every file that uses sql statements?

like image 333
Sun_Blood Avatar asked Aug 24 '12 14:08

Sun_Blood


People also ask

Is MySQLi deprecated in PHP 7?

The oldest one uses the MySQL extension, which was deprecated as of PHP 5.5 and fully removed in PHP 7. The mysql() function no longer works in PHP 7.

Is MySQLi built into PHP?

The MySQLi extension was introduced with PHP version 5.0. 0. The MySQL Native Driver was included in PHP version 5.3.

How do I switch from MySQL to MySQLi?

If you want to convert your script from a MySQL extension to a MySQLi extension manually, you must start with the top of the script and start converting all the methods one by one. For this, open the script in any text editor and use the find-and-replace tool to replace mysql_ with mysqli .

What's the difference between MySQL and MySQLi?

Basically, MySQL is the old database driver, and MySQLi is the Improved driver. The "i" stands for "improved" so it is MySQL improved. MySQLi can be done procedural and object-oriented whereas MySQL can only be used procedurally. Mysqli also supports prepared statements which protect from SQL Injection.


1 Answers

Yes, MySQLi is object oriented and you need to pass around the $db object to the functions that need a database connection. The procedural alternatives also require the $db object to work. This is for your own good, as implicit global connections (actually: global state in any form) are bad practice. That the mysql extension allowed implicit connections was not good to begin with.

like image 80
deceze Avatar answered Oct 21 '22 11:10

deceze