LOKESH LOKESH - 8 days ago 4
MySQL Question

which mysqli query need mysqli_connect

Connection file is as below

$database = "order";
$con = mysqli_connect($host, $username, $password, $database);
$sel_db=mysqli_select_db($con,$database) or die("Cannot Select Database");

In each file I include above connection file

My older code for mysql is like

mysql_query("select * from order_detail");

and new query for mysqli is as below

mysqli_query($con,"select * from order_detail");

Above query required $con for connection

it does not required $con


So my question is that which query required $con as connection


The mysql functions implicitly used the last connection that was made if no connection was explicitly given. Note that you already could pass in a connection, even to the old function as you can read here. This behavior is confusing and error prone, so fortunately they made that more explicit in the mysqli functions.

I'm not sure that is the main reason though. It probably might have more to do with the fact that mysqli also has an object syntax, and that one syntax wraps another. The $con variable in the procedural version and the object instance in the objective version both serve the same purpose: telling the function/method which connection to use. Actually, the doc says that the connection parameter for mysqli_query is a mysqli object instance, so mysqli_query might just be implemented like this as a wrapper function to make it easier to convert your code from mysql to mysqli:

function mysqli_query($link, $query, $resultmode = MYSQLI_STORE_RESULT) {
  return $link->query($query, $resultmode);

If you didn't understand anything I said in this last paragraph, don't worry, it's not really important. ;)

Anyway, while mysql_query performs a query on a connection, mysql_fetch_array fetches values from a query result. The $var your pass to it already contains all the information it needs. It doesn't need a connection at that point, so there is no need to pass it as an argument. There is no mysqli_fetch_array by the way. Instead you should use mysqli_stmt_fetch, to which the same applies: it doesn't need a connection, but a statement object (mysqli_stmt), which represents the query result.

Many of the mysqli functions have the same or similar parameters as their predecessors, but there may be differences. So for every function you use, I'd check the official documentation.

And also, I'd use an IDE or editor that will help you with the function syntax by providing built in code insight. Netbeans for PHP is a quite elaborate one that can be used for free, but there are even better ones (like PHPStorm) if you can spend some money.

PS: If you use prepared statements, you can get rid of mysql_real_escape_string completely.