0

I have a PDO that is querying a non-existant user in the database to handle user registration. The problem is, var_dump and print_r both do not print anything if the user is not found.

    try {
        $stmt->execute();
        while($row = $stmt->fetch()) {
            var_dump($row);
            print_r($row);
            if($row = null) { // Not working
            # if(!isset($row)) { // Not working
            # if(empty($row)) { // Also not working
                echo "User not found";
            } else {
                echo $row['realname']."<br>";
            }
        }
    } catch(PDOException $e) {
        echo "FATAL ERROR OCCURED:".$e->getMessage();
    }

What is happening here? The page is just blank.

php -l index.php repors no syntax errors and the page is not throwing error 500.

Nothing in view source either.

Here is connection details:

try {
    $dbh = new PDO('mysql:host=127.0.0.1;dbname=PHP_PDO', "root", "root", array(
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ));
} catch(PDOException $e) {
    die("FATAL ERROR OCCURED");
}

$stmt = $dbh->prepare("SELECT realname FROM users WHERE name = :name" );

$stmt->bindParam(":name", $name);

$name = "mivuckovaca"; // NOT IN DATA BASE
Gala
  • 2,592
  • 3
  • 25
  • 33

2 Answers2

1

The reason why it's not working, is that you are "assigning" in if($row = null) using 1 equal sign, rather than "comparing" if($row == null) with 2 equal signs (or 3 "if identical", depending on what you want to check for).

Consult: The 3 different equals here on Stack about this.

References:

PHP sees the "assignment" as being valid syntax and that is why you are not receiving any errors.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
1

Turns out i had to reorganize the code a bit.

I took the $row = $stmt->fetch(); out of the while loop, and checked the $row seperately. Like this:

$stmt = $dbh->prepare("SELECT realname FROM users WHERE name = :name" );

$stmt->bindParam(":name", $name);

$name = "mivuckovaca"; // NOT IN DATABSE ON PURPOSE

try {
    $stmt->execute();
} catch(PDOException $e) {
    echo "FATAL ERROR OCCURED:".$e->getMessage();
}

$res = $stmt->fetchAll(); # Replaced fetch() with fetchAll()

if(empty($res)) {
    echo "User not found";
} else {
    foreach($res as $row) { # replaced while() with foreach()
        echo $row['realname'];
    }
}
Gala
  • 2,592
  • 3
  • 25
  • 33