Skip to main content
IBM  
Shop Support Downloads
IBM Home Products Consulting Industries News About IBM
IBM developerWorks : Web Architecture : Education - Tutorials
Writing efficient PHP
ZIPPDF (letter)PDF (A4)e-mail
Main menuSection menuFeedbackPreviousNext
4. Optimizing database queries
  


Handling results sets page 7 of 8


Assuming you've done all you can to optimize your database queries, the next thing to look at is how you access the results within your PHP code.

For now, I assume that you are using the Unified ODBC functions in PHP since these are the most generic. The same concepts apply even if you are using one of the other database-specific sets of functions.

Rather than using something like odbc_result to retrieve individual fields, use odbc_fetch_into to get the entire row into an array then access the array directly. This results in far fewer functions calls especially when iterating over a large record set.

Additionally, when accessing array elements, use numbered indexes rather than named indexes. Although these generally are less readable, they result in faster runtime execution. To address the readability issue, add short comments to indicate which fields are accessed in each case.

Finally, avoid repeated calls (for example, when processing individual records or rows) to the functions such as odbc_field_name, odbc_field_type, odbc_field_len and other odbc_field_* functions. Such functions return the same value for all records in a result set. The number of fields are always the same within a given query, as are the field names, and the type and length of each field. Therefore, if any of these values are required, retrieve them once after making the initial query/ Then, save the result in a local variable that can be referenced as needed for each record.


Main menuSection menuFeedbackPreviousNext
Privacy Legal Contact