note 58875 added to function.is-null
| From: | Art at osu1 dot php dot net | Date: | Fri, 18 Nov 2005 17:32:24 +0000 |
| Subject: | note 58875 added to function.is-null | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-98759@lists.php.net to get a copy of this message | ||
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?
----
Manual Page -- http://www.php.net/manual/en/function.is-null.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+58875
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+58875&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+58875&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+58875&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+58875&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+58875&report=yes&reason=non-english
Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+58875&report=yes&reason=already+in+docs
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+58875&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+58875&report=yes
Search -- http://master.php.net/manage/user-notes.php