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.
There are some things to clarify
- 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.
- So, you're talking of just using connection resource variable.
- Yes, you have to pass it in every function. Not a big deal, nothing to talk of.
- The only issue could be with variable scope. Use
global $db; inside a function.
- 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.
- The only reason (quite weak though) for move - to use prepared statements.
- Mysqli's support for prepared statements is awful
- So, better quit mysqli and go for PDO
- 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.