I’ve got a PHP function which receives some parameters. Each parameter corresponds to a VALUE of one SQL line.
What I would like to do, is to update the values according to the parameters ; but with having some parameters not mandatory. So if a parameter is set to ‘keep’, the VALUE has to keep its current value. This is where I’m stuck.
Here is the function :
function upt($id, $p1, $p2)
{
if ($p1 === 'keep')
$p1 = 'columnName1';
if ($p2 === 'keep')
$p2 = 'columnName2';
$REQ = $DB->prepare('UPDATE ms_cart_products SET columnName1=:P1, columnName2=:P2 WHERE ID=:ID');
$REQ->execute(array(
':P1' => $p1,
':P2' => $p2,
':ID' => $id));
$REQ->closeCursor();
}
Obviously, this does not work (even if I had the secret hope that making $p1 = ‘columnName1’ would work as if I made COL1=COL1 directly in the SQL console).
The VALUE is literally set to ‘columnName’.
Any ideas ?
Thank you,
Florian
Let’s assume that you use either PostgreSQL or MySQL (I don’t mention other RDBMSes here, please tell us if you use something else). Then you can write an
UPDATElikeNULLIFreturns its first value when the too values provided are different, otherwise it returnsNULL.COALESCEthen returns the first non-NULL value. This way, if you pass ‘keep’ to this expression, the innerNULLIFpart evaluates to NULL, therefore theCOALESCEreturns the value kept incolumnName1. Otherwise theNULLIFreturns the passed value andCOALESCEevaluates to that.See the docs:
http://www.postgresql.org/docs/9.1/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL
or
http://dev.mysql.com/doc/refman/5.5/en/control-flow-functions.html#function_nullif
http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_coalesce