João Dias
João Dias

Reputation: 1108

Query returns null

Hello I've got this query to get users by email, which is an unique field in the db.

However, when i want to get the data on it, it simply returns null.

Here's the code

    public function getUserByEmail($email)
    {

            $statement = "SELECT id_user,nome,email,permissao,activo FROM sys_users 
                          WHERE email=$email";

            try
            {

             $sth = $this->db->query($statement);
             $sth->setFetchMode(PDO::FETCH_OBJ);
             $rcs_users = $sth->fetchAll();
             return $rcs_users;

            }
            catch(PDOException $e)
            {
                "DB Error".$e->getMessage();
            }

    }

And the respective function call

$user_rcs = $user->getUserByEmail($email);

    var_dump($user_rcs); //returns null




    $_SESSION['email'] = $email;
    $_SESSION['user'] = $user_rcs->nome;
    $_SESSION['permissao'] = $user_rcs->permissao;

And then I get this error

Notice: Trying to get property of non-object in C:\xampp\htdocs\inacesso\admin\modules\auth\authhandler.php on line 24

Glad if you could help me!

Upvotes: 2

Views: 896

Answers (2)

Brad Christie
Brad Christie

Reputation: 101594

First off, seriously have a look at PDO.

Secondly I would imagine the email column is a string. As such, you'll need to surround $email with quotes in your query (after having sanitized it vigorously of course...)

WHERE email='$email'

PDO version:

$pdo = new PDO(...);
$query = $pdo->prepare('SELECT id_user,nome,email,permissao,activo '.
                       'FROM   sys_users '.
                       'WHERE  email = ?');
$result = $query->execute(array($email));

Upvotes: 1

Quentin
Quentin

Reputation: 943108

Strings in SQL have to be quoted, so unless $email arrives in the function with ' and ' around it, the SQL will error.

But you shouldn't be building SQL by mashing together PHP strings anyway. Use PDO or mysqli_* with bound parameters (and prepared statements) and that will take care of quoting (and escaping) for you.

Upvotes: 5

Related Questions