does try catch work with mysql?

Status
Not open for further replies.

Stanley

Banned
Jun 24, 2006
3,399
43
0
San Diego
can php exceptions (try & catch) be used with mysql queries?

like, if the mysql query fails how do I initialize the try{} block?

I've never used exceptions so I'm not sure how it works.
 


Sure.

It'd be best to write a new MySQLException class that extends the built in exception class.

I'll try and dig up an example that I've used in the past for object creation (but it will work in a similar way).
 
Quick and dirty would be to just wrap your query calls in a function and throw an exception when an error occurs. Then you can catch your exception wherever you actually run your query.

PHP:
connect();

try{
	var_dump(query("select value from table"));
}
catch(Exception $e)
{
	 // user friendly error message
         print "Exception caught " . $e->getMessage();
         // maybe write the full error to a log file here
}

function query($q)
{
	$res = mysql_query($q);
	if(!$res)
		throw new exception("Bad Query");
	return $res; // only executes if $res is ok
}

The ideal solution would be as mentioned, to write your own error handling. I personally prefer to use a DB abstraction layer like PDO though, which throws its own exceptions.
 
I wouldn't call that quick & dirty by any means. It works, and I've seen several sites use methods similar to that in the past.

Stanley - are you trying to figure out of the MySQL query is an invalid query (i.e. MySQL Error) or if it just returns no rows.
 
I never did find that MySQL class...

If you want something more "polished" than what aim posted you'll have to write some type of MySQL class that you can use to run queries and work your try/catch blocks into that.
 
I wouldn't call that quick & dirty by any means. It works, and I've seen several sites use methods similar to that in the past.

Stanley - are you trying to figure out of the MySQL query is an invalid query (i.e. MySQL Error) or if it just returns no rows.
need to know if it's an invalid query (i.e. couldn't connect to table or some shit like that)
 
Status
Not open for further replies.