Question Overflow
Question Overflow

Reputation: 11275

Working with possible null value in the where clause of a PDO query

I have an SQL query that goes like this:

$stmt = $dbh->prepare("SELECT userID FROM User WHERE areaCode=? AND contactNo=?");
$stmt->bindValue(1, $areaCode ? $areaCode : null, PDO::PARAM_INT);
$stmt->bindValue(2, $contactNo, PDO::PARAM_INT);
$stmt->execute();

When $areaCode is null, this query would fail because areaCode=null needs to be tested with areaCode IS NULL instead. Is it still possible to parameterized such query?

Upvotes: 0

Views: 145

Answers (1)

Alma Do
Alma Do

Reputation: 37365

You can do that (i.e. parametrize) via <=> operator:

$stmt = $dbh->prepare("SELECT userID FROM User WHERE areaCode <=> ? AND contactNo=?");

Upvotes: 3

Related Questions