Error handling in PHP4 with MySQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
flycast
Forum Commoner
Posts: 37
Joined: Wed Jun 01, 2005 7:33 pm

Error handling in PHP4 with MySQL

Post by flycast »

I am working in PHP4 (I know, 5 is better with try...catch but I can't help the PHP4 decision). Anyway, I need to make sure that if a MySQL query creates certain errors (no table by that name and no field by that name) that the rest of the script executes but I can let the user know that an error occurred. My code has an array of queries and if one of the queries has an error then the script stops and the error is displayed. Like this:
MySQL ERROR:

Error Number: 1054

Description: Unknown column 'field_name_test' in 'field list'

Query: INSERT INTO `exp_weblog_fields` (`field_name_test`) VALUES ('testing123')
What recommendations do you all have to deal with the error but not kill the script?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Error handling in PHP4 with MySQL

Post by requinix »

mysql_query returns false if the query is invalid. This happens, among other reasons, if a table or field doesn't exist.
mysql_errno gives you the MySQL error number of the last failed query.

Adjust your error handling code to check mysql_errno before erroring-out like it normally would. The "unknown table" message's error number is 1109.
Post Reply