2

I have a simple PHP login function. Within this function, I am checking to see if the user exist by making a MySQL query that is selecting username from a table and counting the number of rows that is returned. I am having trouble with the query returning null when I know for a fact that the table contains the username.

Here is my code.

function login($user_name, $password) {
    $db1 = new DB_CONNECT();        
    $db1->connect();

    $query = "SELECT user_name FROM users WHERE user_name = '$user_name'";
    $result = $db1->makeAQuery($query);

    if (mysql_num_rows($result) == 1) {
        //check the password
    }
    else {
        //no user exist 
    }
}


I know that the username and password that are coming in are OK and I trim for any white spaces before I sent them to the function. I know that the database connection is working because it works on the rest of my PHP code. The only error that I am getting is one that mentions that the mysql_num_rows "expects parameter 1 to be resource, null given"

Database class

class DB_CONNECT {
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

        // Selecing database
        mysql_select_db(DB_DATABASE, $con) or die(mysql_error());
    }
    function makeAQuery($query) {
        $result = mysql_query($query) or die(mysql_error());        
    } 
    function close() {
       // closing db connection
    mysql_close();
    }
}
9

2 Answers 2

2

This should work:

"SELECT user_name FROM users WHERE user_name = '".$user_name."'";

Also

change this:

function makeAQuery($query) {
    $result = mysql_query($query) or die(mysql_error());        
} 

to

function makeAQuery($query) {
    $result = mysql_query($query) or die(mysql_error());      
    return   $result;
} 
Sign up to request clarification or add additional context in comments.

1 Comment

The Return statement did it. After all that, I forgot a simple statement.
-1

Maybe try removing the spaces between the = in the query.

"SELECT user_name FROM users WHERE user_name='$user_name'"

Your script may be returning null because the query could not run.

3 Comments

i can make it WHERE user_name = many_space_here '$user_name' and it will work
Ah sorry, I forgot MySQL does not care for whitespace.
With or without spaces, the samething

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.