$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
if(!result) echo 'error';
(or)
// assume connection to database is established in the beginning itself
if($result = mysql_query("SELECT * FROM `table`")) // do something
else echo 'error';
I guess both perform the same operation indeed. If it is wrong correct me.The question is why does people like to prefer this syntax mysql_query($query, $connection);
, is it some standard to follow or user preference? or do they differ in functionality.
and also kjndly clear me this, what could be the cause for mysql_query
to return false or fail to execute? and the functions like mysql_num_rows,mysql_fetch_array
do they also fail to execute at times due to server or database issues?
kindly let me know and it would be greatly appreciated. Thanks
It is preferred to split them apart because it is far easier to debug. For example:
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
if(!result) echo "error with query $query"; // You can print the query for easy debugging
or allow for simple debugging:
$query = "SELECT * FROM `table`";
if($debug) echo $query;
The mysql_fetch_* will not fail if you already checked your result (like in the above code). If there was an error executing the query then all the code down the line will fail. We see far too much code here that never checks error codes and handle the errors properly before trying to get results.
Hope this helps. As noted in the comments. It would be much preferred to NOT use the mysql_* functions as they are deprecated.