Database Reference
In-Depth Information
Ruby
Ruby DBI represents NULL values using nil , which can be identified by applying the
nil? method to a value. The following example uses nil? to determine whether to print
result set values as is or as the string "NULL" for NULL values:
dbh . execute ( "SELECT name, birth, foods FROM profile" ) do | sth |
sth . fetch do | row |
for i in 0 . . . row . length
row [ i ] = "NULL" if row [ i ]. nil? # is the column value NULL?
end
printf "id: %s, name: %s, cats: %s \n " , row [ 0 ] , row [ 1 ] , row [ 2 ]
end
end
A shorter alternative to the for loop is the collect! method, which takes each array
element in turn and replaces it with the value returned by the code block:
row . collect! { | val | val . nil? ? "NULL" : val }
PHP
PHP represents SQL NULL values in result sets as the PHP NULL value. To determine
whether a value from a result set represents a NULL value, compare it to the PHP NULL
value using the === “triple equal” operator:
if ( $val === NULL )
{
# $val is a NULL value
}
In PHP, the triple equal operator means “exactly equal to.” The usual == “equal to”
comparison operator is not suitable here: with == , PHP considers the NULL value, the
empty string, and 0 all equal.
The following code uses the === operator to identify NULL values in a result set and print
them as the string "NULL" :
$sth = $dbh -> query ( "SELECT name, birth, foods FROM profile" );
while ( $row = $sth -> fetch ( PDO :: FETCH_NUM ))
{
foreach ( array_keys ( $row ) as $key )
{
if ( $row [ $key ] === NULL )
$row [ $key ] = "NULL" ;
}
print ( "name: $row[0] , birth: $row[1] , foods: $row[2] \n " );
}
An alternative to === for NULL value tests is is_null() .
Search WWH ::




Custom Search