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 $mac
and 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?
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:
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