Article

Beginning Databases with PostgreSQL - Chapter 15: Accessing PostgreSQL from PHP

Page: 1 2 3 4 5 6 7 8 9 10 11 12 Next

Field Information

PHP allows you to gather some information on the field values in your resultset. These functions may be useful in certain circumstances, so we will cover them briefly here.

pg_fieldisnull()

PostgreSQL supports a notion of NULL field values. PHP doesn't necessarily define NULL the same way PostgreSQL does, however. To account for this, PHP provides the pg_fieldisnull() function so that you may determine whether a field value is NULL based on the PostgreSQL definition of NULL:

if (pg_fieldisnull($result, $row, $field)) {        
   echo "$field is NULL.";        
} else {        
   echo "$field is " . pg_result($result, $row, $field);        
}

pg_fieldname() and pg_fieldnum()

These functions return the name or number of a given field. The fields are indexed numerically, starting with zero:

echo "Field 1 is named: " . pg_fieldname($result, 1);        
echo "Field item_id is number: " . pg_fieldnum($result, "item_id");

Note that pg_fieldname() will return the field name as specified in the SELECT statement.

pg_fieldsize(), pg_fieldprtlen(), and pg_fieldtype()

The size, printed (character) length, and type of fields can be determined:

echo "Size of field 2:" . pg_fieldsize($result, 2);        
echo "Length of field 2: " . pg_fieldprtlen($result, $row, 2);        
echo "Type of field 2: " . pg_fieldtype($result, 2);

As usual, the numeric field indices start at zero. Field indices may also be specified as a string representing the field name.

Also, if the size of the field is variable, pg_fieldsize() will return a -1, or false on an error. pg_fieldprtlen() will return -1 on an error.

Freeing Resultsets

pg_freeresult()

It is possible to free the memory used by a resultset by using the pg_freeresult() function:

pg_freeresult($result);

PHP will automatically free up all result memory at the end of the script's execution anyway, so this function only needs to be called if you're especially worried about memory consumption in your script, and you know you won't be using this resultset again later on in your script's execution.

Type Conversion of Result Values

PHP does not offer the diverse data type support you might find in other languages, so values in resultsets are sometimes converted from their original data type to a PHP-native data type. For the most part, this conversion will have very little or no effect on your application, but it's important to be aware that some type conversion may occur:

  • All integer, boolean, and OID types are converted to integers
  • All forms of floating point numbers are converted to doubles
  • All other types (arrays, etc.) are represented as strings

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links