Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Mysqli: Is there a way to not have to connect to the database every single query?

I have just begun working with MYSQLi instead of MYSQL, and I have run into a huge annoyance: having to connect to the database every single query and such. Why do I have to do this now when I didn't in old MYSQL? Or is there a way not to have to do this?

A couple examples:

Mysql:

mysql_query("SELECT id FROM table");

Now in Mysqli I always have to do:

mysqli_query($db, "SELECT id FROM table");

also I have to do this with:

mysqli_last_id($db);

and

mysqli_real_escape_string($db);

I have tried to find the answer to this all night, but I can't find anything.

like image 200
Dylan Cross Avatar asked Dec 05 '25 15:12

Dylan Cross


1 Answers

There are some things to clarify

  1. You don't have to connect every time. Connecting to database is different thing, one when you're calling mysqli_connect() and you should do it only once per application.
  2. So, you're talking of just using connection resource variable.
  3. Yes, you have to pass it in every function. Not a big deal, nothing to talk of.
  4. The only issue could be with variable scope. Use global $db; inside a function.
  5. Moving to mysqli just mechanically, using new functions old way makes absolutely no sense. If you want to keep using mysqli_real_escape_string in the application code - don't bother with transition at all and keep with mysql.
  6. The only reason (quite weak though) for move - to use prepared statements.
  7. Mysqli's support for prepared statements is awful
  8. So, better quit mysqli and go for PDO
  9. Nevertheless, using raw API functions, be it mysql, mysqli or PDO, is ugly. One have to adopt some abstraction library to be used in the application code instead.
like image 52
Your Common Sense Avatar answered Dec 07 '25 05:12

Your Common Sense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!