Search code examples
phpmysqlauthenticationmysql-num-rows

mysql and php login page with mysql_num_rows


I have those codes and its give me an error 'Warning: mysql_num_rows() expects parameter 1 to be resource' :

PHP:

<?php
@error_reporting(0);
@session_start();
@include("sql.php");
$log_error = "";

if(isset($_POST['send'])) {
$user = protect($_POST['username']);
$pass = protect($_POST['password']);
$q = mysql_query("SELECT * FROM login WHERE name = '".$user."' and pass = '".$pass."'",$sqlc);
$count = mysql_num_rows($q);

if($count > 0) {
    $_SESSION['username'] == $user;
    header('Location: index.php');
    $log_error = "0";
} else {
    $log_error = "1";
}
}
?>

HTML:

<table border="0">
        <form action="" method="post">
            <tr>
                <td colspan="2" style="width:100%;"><span>Login</span></td>
            <tr>
            <tr>
                <td>Username:</td>
                <td><input type="text" name="username" value="" /></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="password" name="password" value="" /></td>
            </tr>
            <tr>
                <td colspan="2" style="width:100%;"><input type="submit" name="send" value="Login" /></td>
            </tr>
            </form>
        </table>

And the SQL connection (sql.php):

<?php
$Host = 'localhost';
$User = 'dash_sys1';
$Pass = '123456Ben';
$DB = 'dash_sys1';

$sqlc = mysql_connect($Host,$User,$Pass) or die(mysql_error());
mysql_select_db($DB) or die(mysql_error());
function protect($str) {
return htmlspecialchars(mysql_real_escape_string(trim($str)));
}
?>

its gives me that error: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\cms\admin\login.php on line 11

what I did wrong?


Solution

  • Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given

    This means that you passed a non-resource to the function. So why would $q be a non-resource? The mysql_query() function returns a boolean false value if you have an error in your SQL query or usage of the function. So $q is assigned the false value, not a query result resource. Then you pass $q to mysql_num_rows() and that's not going to work.

    You should always check the return value of mysql_query() for the false result.

    $q = mysql_query("SELECT * FROM login WHERE name = '".$user."' and pass = '".$pass."'",$sqlc);
    if ($q === false) {
        trigger_error(mysql_error($sqlc), E_USER_ERROR);
    } else {
        $count = mysql_num_rows($q);
    }