I got 2 columns in my database that hold text (Products Code and Products Variant).
for example:
Products Code holds the following text: C050101, C070104
and
Products Variant holds the following text: RED, NULL
I want to select all the rows WHERE Code = Products Code AND Variant = Products Variant.
bases on the example I wrote above, I should get 2 rows:
first row WHERE Code=C050101 and Variant=RED
second row WHERE Code=C070104 and Variant IS NULL << IS NULL
I have no idea how to do it…
I would know how to do it if I only need to select only all the rows WHERE Code = Products Code >>
$arr = array('C050101','C070104');
$inclause = implode(',',array_fill(0,count($arr),'?'));
$stockstmt = $pdo->prepare(sprintf("SELECT `id`, `WebTitle`, `StockCode` FROM `stock` WHERE `StockCode` IN(%s)",$inclause));
$stockstmt->execute($arr);
I would really appreciate your help.
Thanks!
You can’t use the
INpredicate for this becauseINonly knows how to compare with=and you need to compare differently to handle the NULLs.MySQL has a non-standard null-safe equal operator
<=>which knows that NULL=NULL is true, and NULL = ‘RED’ is false.If you use something other than MySQL, your RDBMS might support
IS [NOT] DISTINCTwhich is standard SQL syntax for a similar predicate.I tested the following and it works:
I’ll leave it to you how you want to build a list of predicates.
Re your comment:
It’s not a recommended practice to use the literal string ‘NULL’ to represent a missing or inapplicable value. That’s what NULL is for in SQL.
If you want a function that makes it more dynamic to build the predicates, try this:
Be careful that the keys of the array you pass are legitimate column names. That is, don’t let user input ever set the column names unless you verify it against a whitelist of real columns.