PHP / MySQL Query Function

I decided it was time to stop writing out 5 lines or more per MySQL query and instead, create a function to encapsulate that query, and run some tests on the result to determine a result to be returned back.

The query is multi purpose, just like the original mysql_query. But, instead of, after the query, having to test if there is an error, test if the number of rows is greater than 0, or test if an update query affected rows or not, I decided that all that text would fit well in a function.

The readability of the code doesn’t change, since the result returned is either a boolean, or an array.

The other functions surrounding mysql, such as num_rows, etc are not affected as they also work.

The errors when found can be trapped using an error trapping function (which is done).

It’s multi directional, you can get anything you like returned, from a boolean true / false, or a number of records, or, the result set itself.

So, when I query, using the function, it’s now:

1. Build query string.
2. Execute query through new function.
3. Test if it returned false.
.. else, use the data returned in the application.

This is much more efficient compared to the previous manner, where:

1. Build query string.
2. Execute query.
3. Test if the query was successful.
4. Test if there was a mysql error.
5. Test if there is a record or not.
else.. use the data returned in the application.

I’d go and do more, such as bring back an array, instead of a result pointer, but then, I might not want to work with an array, or I might want to have field names.

I already had a function made (and always use) that I escape data with before sending to the database. This works best, because if a new way of exploiting HTML is found, a patch is pretty quick compared to patching page after page of code.

Though, one might go as far as making seperate functions for selecting, updating, etc. I don’t see them changing in the near future, without some form of failsafe for older applications.

Enjoy!

This entry was posted in Programming, Random. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *