note 58875 deleted from function.is-null by nlopess

From: Date: Fri, 18 Nov 2005 19:27:18 +0000
Subject: note 58875 deleted from function.is-null by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-98778@lists.php.net to get a copy of this message
Note Submitter: Art ---- I have an interesting situation: I have a function that handles updating rows where I send in an associative array of $array[column_name] => value. While it works perfectly on building the correct query, it balks at NULL. example: <?php $id = 12; $vars = array( "student_name" => "Art", "ProjectID" => NULL ); modifyRow("students", "id = ".$id, $vars); // The function.. function modifyRow($table, $condition, $data) { //get table info $col_names = getColNames($table); //compose SQL $fields = array(); foreach ($data as $key=>$value){ if ($col_names[$key]) { if (is_null($value)) { $fields[] = "$key = NULL"; } else { $fields[] = "$key = '$value'"; } } } $sql = "UPDATE $table SET ". implode(",",$fields) ." WHERE $condition;"; echo $sql; ... .... ....... } ?> In the above, the output is: UPDATE students SET student_name = 'Art', ProjectID = '' WHERE id = 12 The NULL value in the array is somehow changing to '' (an empty string). I guess this has something to do with array typing? I remember when working with postgreSQL, there was a special character set I could send in to force the array value to retain the NULL value as opposed to an empty string. My only work around is sending in an actual string 'NULL' which is really not an elegant way to do it: <?php $vars = array( "student_name" => "Art", "ProjectID" => 'NULL' ); modifyRow("students", "id = ".$id, $vars); ... ... ... if ($value == 'NULL') { $fields[] = "$key = NULL"; } else { $fields[] = "$key = '$value'"; } ... ... ... ?> Outputs correctly now: UPDATE students SET student_name = 'Art', ProjectID = NULL WHERE id = 12 Any suggestions?

« previous php.notes (#98778) next »