mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows expects parameter 1 to be resource
This is the issue :
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
while($row = mysql_fetch_array($result)) {
echo $row['FirstName'];
}
A query may fail for various reasons -
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
}
mysqli extension
(1)
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");
// mysqli_query returns false if something went wrong with the query
if($result === FALSE) {
yourErrorHandler(mysqli_error($mysqli));
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
(2)
$username = $mysqli->escape_string($_POST['username']);
$result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");
if($result === FALSE) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else {
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
(3) using a prepared statement:
$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?');
if ( !$stmt ) {
yourErrorHandler($mysqli->error); // or $mysqli->error_list
}
else if ( !$stmt->bind_param('s', $_POST['username']) ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else if ( !$stmt->execute() ) {
yourErrorHandler($stmt->error); // or $stmt->error_list
}
else {
$result = $stmt->get_result();
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) {
...
It will manifest itself when using:
-
mysql_fetch_array
/mysqli_fetch_array()
-
mysql_fetch_assoc()
/mysqli_fetch_assoc()
-
mysql_num_rows()
/mysqli_num_rows()
0 comments:
Post a Comment