home support FAQ resources services partners contact us contact us
 MySQL Tutorial Previous  Next  
 

# fetch all rows into a reference to an array of references

my $matrix_ref = $dbh->selectall_arrayref ($query);

# determine dimensions of matrix
my $rows = (!defined ($matrix_ref) ? 0 : scalar (@{$matrix_ref}));
my $cols = ($rows == 0 ? 0 : scalar (@{$matrix_ref->[0]}));

for (my $i = 0; $i < $rows; $i++) # print each row
{
my $delim = "";
for (my $j = 0; $j < $cols; $j++)
{
$matrix_ref->[$i][$j] = "" if !defined ($matrix_ref->[$i][$j]); # NULL?
print $delim . $matrix_ref->[$i][$j];
$delim = ",";
}
print "\n";
}

Checking for NULL Values

When you retrieve information from a database, you may need to distinguish between column values that are NULL and those that are zero or empty strings. This is easy to do because DBI returns NULL column values as undef. However, you must be sure to use the correct test. If you try the following code fragment, it prints "false!" all three times:

$col_val = undef; if (!$col_val) { print "false!\n"; }
$col_val = 0; if (!$col_val) { print "false!\n"; }
$col_val = ""; if (!$col_val) { print "false!\n"; }
What that demonstrates is that the form of the test is unable to distinguish between undef, 0, and the empty string. The next fragment prints "false!" for both tests, indicating that the test cannot distinguish undef from the empty string:

$col_val = undef; if ($col_val eq "") { print "false!\n"; }
$col_val = ""; if ($col_val eq "") { print "false!\n"; }
This fragment prints the same output, showing that the second test fails to distinguish 0 from the empty string:

$col_val = "";
if ($col_val eq "") { print "false!\n"; }
if ($col_val == 0) { print "false!\n"; }

To distinguish between undef (NULL) column values and non-undef values, use defined(). After you know a value doesn't represent NULL, you can distinguish between other types of values using appropriate tests—for example:

if (!defined ($col_val)) { print "NULL\n"; }
elsif ($col_val eq "") { print "empty string\n"; }
elsif ($col_val == 0) { print "zero\n"; }
else { print "other\n"; }

It's important to perform the tests in the proper order because both the second and third comparisons are true if $col_val is an empty string. If you reverse the order of those comparisons, you'll incorrectly interpret empty strings as zero.
)
Previous  Next  
Link Partners: Asia florist, Flowers to India, Hong kong flowers, Site submit, Cheap web hosting, China florist, Japan florist