Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

Ive recently been learning about OOP and PDO and think its really great but Im having a problem trying to convert some code from procedural programming to OOP.

I have some code to log in that checks that the query I run (using prepared statement) isnt empty, and the results of the query is stored in a variable.

PHP
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];


$db = Database::getConnection();

if ($username&&$password)
{

$sqlQuery = "SELECT * FROM users WHERE username=:username";

$loginUser = $db->prepare($sqlQuery);

$loginUser->execute(array(':username' => $username));

if ($loginUser!=0)
{
//Do a while statement and store username, password, activated into variables
} else {
echo "User Doesnt Exist!";
}
}


The Problem is, is that I keep getting an error on the line "if ($loginUser!=0)" and I think its because there may be another method in OOP to check the SQL isnt empty.

Note: the Error I get is: "Notice: Object of class PDOStatement could not be converted to int...".

Many thanks for any help.
Posted
Updated 1-Dec-14 3:43am
v2

1 solution

Why some non-numeric object could be 0? From your code sample, it is apparent that $loginUser is an instance of some class (it has execute method, for example). So, you need this:
http://php.net/manual/en/function.is-null.php[^].

Note that the change in the if statement would not make your code correct. You are thinking about a check which is would be too late. For example, you are trying to call $loginUser->execute before the check, but in case where $loginUser is null, you would be dereferencing null object, which would throw the exception.

—SA
 
Share this answer
 
Comments
jba1991 1-Dec-14 11:23am    
Would it work if I do "if(empty($loginUser))" and in the else statement execute the code to log in?
Sergey Alexandrovich Kryukov 1-Dec-14 11:26am    
Why not? But it would work only if $loginUser is not null, and would be useful if an empty object may appear in your case. Empty objects are not null.
—SA
jba1991 1-Dec-14 11:36am    
I just looked for the difference between empty and null, using empty will not work for me in this case i dont think.

What if I used "if($loginUser === NULL)"?
Sergey Alexandrovich Kryukov 1-Dec-14 14:02pm    
Is it a kind of another question? The whole concept of "difference between empty and null" is nonsense. What is "difference"?

I told you how to do the check correctly; what's the problems with it?
=== is the "identity" operator; you can read about it.

—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900