CMArg CMArg - 4 years ago 88
PHP Question

SQL update to NULL using a variable

I keep having problems with quotes in relation to a table update. I'm sending a Post with several values from a form, and then update a table with them. For the code to work, I need to wrap keys with backslash (

$ColumnaString
), and values with single quotes (
$ValueString
). This works OK. My problem is that occasionally I want to update to NULL (when
$value==""
). But my present code don't do that. Can somebody spot the problem?

$id_tag=trim($_POST['id']);
foreach($_POST as $key=>$value){
if ($key!="UpdatePeople"){
$ColumnaString="`".$key."`";
$ValueString="'".iconv('UTF-8', 'ISO-8859-1//TRANSLIT', utf8_encode($value))."'";
if ($key=="In_Date" and $value=="") {$ValueString==NULL;} //Hereis my problem I think
$link->query("UPDATE MyTable SET ".$ColumnaString."=".$ValueString." WHERE `id`=".$id_tag."");
}
}

Answer Source

You could check $id_tag and create a proper part of sql code

$str = ($id_tag ='' ) ? ' is null ' : ' = '.$id_tag;

$link->query("UPDATE MyTable SET ".$ColumnaString." = ".$ValueString." WHERE `id`".str."");

and for $vale

if ($key=="In_Date" and $value=="") { $ValueString = 'NULL' ;} //Hereis my problem I think
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download