Search code examples
phpfunctionpdoreturnboolean

My function returns true when I expect false


I am confused as to why my code returns true when I expect false and the other way around. Here's my code:

public function CheckMac($mac){
    $database = new Database();
    $db = $database->connectDatabase();
    $checkedmac = $db->prepare("SELECT * FROM `displays` WHERE `displayMac` = '$mac'");
    $checkedmac->execute();
    $count = (int)$checkedmac->fetchColumn();
    if ($count > 0) {
        return true;
    } else {
        return false;
    }
}

I have the query right, when I echo $macand put it inside the query, phpMyAdmin gives me back the expected line, since it exists in the database, but when I run this code, I'm getting a false return.

Where did I go wrong on this one?


Solution

  • There is a fantastic yet underestimated answer, If your code is doing something unexpected, there's a good chance you're making an assumption somewhere.

    You are yet to learn the cornerstone concept in the art of programming called debugging. Which means you are supposed to verify every single assumption you made.

    You are assuming here that when a query returns a row, the (int)$checkedmac->fetchColumn(); statement returns a positive number. So you have to verify it.

    I can make an assumption that the first column in your table does not contain a positive number but rather a string. A string cast a number will return 0. It will explain why you're getting 0 when a record is found. But you have to verify it as well.

    If my assumption proves to be true, simply select a constant value instead of rather uncertain *. You can use 1 for example, and your query will work flawlessly:

    public function CheckMac($db, $mac){
        $stmt = $db->prepare("SELECT 1 FROM `displays` WHERE `displayMac` = ?");
        $stmt->execute([$mac]);
        return $stmt->fetchColumn();
    }
    

    A couple notes:

    • you should always connect only once. Create a $db variable beforehand in a single place and then use it everywhere
    • you are using a cargo cult prepared statement that protects from nothing. It should be always the way shown in my example.
    • if ($count > 0) return true is a tautology. A $count > 0 statement already returns true or false, so you can return its result rigtht away, without a superfluous condition
    • moreover, 1 is as good as true in PHP. So in the end you can return the result of fetchColumn() right away. in case the row is found it will be 1 equal to true and just false otherwise.