mysql_query() returning boolean and causing mysql_fetch_assoc() to fail
mysql, php
Solution
`mysql_query()` returns false if there's an error. If it returns false, you can get the error message with `mysql_error()`, which should give you a hint about what's wrong with the query.
This is why you used to see a lot of these style queries:
$result = mysql_query('SELECT foo FROM bar') or die(mysql_error());
Problem
I'm writing a small login class for an application of mine, however, I think my query is bad, because when I call `mysql_fetch_assoc()` on the result of the query, I get this error: Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given I'm familiar with how `mysql_fetch_assoc()` works, but I'm guessing the call to `mysql_query()` is returning false, which is obviously a boolean, producing the error. Here's the query: ``` $loginsql = 'SELECT userid, username, password FROM users WHERE username=\'. $username .\' AND password=\'. $password .\''; ``` Note: I realize the "mysql_" function set in PHP is deprecated as of 5.5, but I'm using 5.3.8 and just practicing. I will refactor the application later using PDO. classes.php ``` <?php class connectToDb { function dbConnect($config) { $connection = mysql_connect($config['host'], $config['dbuser'], $config['dbpass']); if ($connection) { mysql_select_db($config['db'], $connection); } else { echo "Could not connect to database!"; } } } class registerAccount { function doRegister($regusername, $regpassword, $regemail) { $regsql = "INSERT INTO users (username, password, email) VALUES ('$regusername', '$regpassword', '$regemail')"; if (mysql_query($regsql)) { echo "Successfully registered!"; } else { echo "Problem with registration!"; } } } class loginAccount { function doLogin($username, $password) { mysql_real_escape_string($username); mysql_real_escape_string($password); hash('sha256', $password); $loginsql = 'SELECT userid, username, password FROM users WHERE username=\'. $username .\' AND password=\'. $password .\''; $result = mysql_query($loginsql) or die(mysql_error()); $loginrow = mysql_fetch_assoc($result); if ($loginrow) { $_SESSION['username'] = $loginrow['username']; $_SESSION['userid'] = $loginrow['userid']; } else { echo "Incorrect username and/or password!"; } } } ```