All we need is an easy explanation of the problem, so here it is.
I work with xampp. I performed MySQL connection:
$connection = mysql_connect($host , $user , $passw); mysql_select_db($db, $connection);
I received output with echo command (by check the boolean returned values) that connection is established and the database $db is found.
But the simplest query like:
$query = mysql_query("SELECT * FROM 'users'");
returns false. How can I debug why?Thanks.
How to solve :
I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.
An obligatory update: as mysql ext is no more, here are answers for two remaining MySQL APIs which I written on my site based on the experience from answering 1000s questions on Stack Overflow:
- How to report errors in mysqli
- How to connect to MySQL using PDO (with the aim of the proper error reporting).
In short, for mysqi the following line have to be added before
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
while for PDO the proper error mode have to be set, for example
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
As of the old mysql ext,
To get an error from
mysql_query() you have to use
So always run all your queries this way, at least until you develop a more advanced query handler:
$query = "SELECT * FROM 'users'"; $result = mysql_query($query) or trigger_error(mysql_error()." ".$query);
the problem with your current query is
'users' part. Single quotes have to be used to delimit strings while for the identifiers you have to use backticks:
SELECT * FROM `users`
In order to see these errors during development, add these lines at the top of your code to be sure you can see every error occurred
on the production server, however, the value on the first line should be changed from 1 to 0
Use the mysql_error() function:
$query = mysql_query("SELECT * FROM 'users'") or die(mysql_error());
EDIT: Per Col. Shrapnel’s comment: you should never use die() outside of a test environment. In general it’s bad practice when writing code that’s even intended for production.
Here is some more information: http://www.phpfreaks.com/blog/or-die-must-die
Based on Your Common Sense answer this is an object oriented style:
$query = "SELECT * FROM 'users'"; $result = $mysqli -> query($query) or trigger_error($mysqli -> error." ".$query);
Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂