Instead of sending queries to PHPs mysql_query()
function I currently send my queries to a custom wrapper sql_query(), which, amongst other things does the "mysql_query" part.
The problem with this setup is that when there's an SQL error the file and the line number are where the sql_query() function is located, rather then where the actual SQL que开发者_开发问答ry is.
Is there a way of having PHP report the file and linenumber of where sql_query() is called from, rather than where the mysql_query()
function actually is?
debug_backtrace
And many helpful example there for your problem. One of this. Surprisingly, no one has described one of the best uses of this: dumping a variable and showing the location. When debugging, especially a big and unfamiliar system, it's a pain remembering where I added those var dumps. Also, this way there is a separator between multiple dump calls.
<?php
function dump( $var ) {
$result = var_export( $var, true );
$loc = whereCalled();
return "\n<pre>Dump: $loc\n$result</pre>";
}
function whereCalled( $level = 1 ) {
$trace = debug_backtrace();
$file = $trace[$level]['file'];
$line = $trace[$level]['line'];
$object = $trace[$level]['object'];
if (is_object($object)) { $object = get_class($object); }
return "Where called: line $line of $object \n(in $file)";
}
?>
You need the stack trace. It's usually in the error context, otherwise you can use libraries like xdebug to fetch one.
Can you pass this information to the wrapper using __FILE__ and __LINE__
constants.
You should add some error-handling to your sql_query(). You could check this functions:
mysql_errno and mysql_error and in case of you have any error raise an exception.
精彩评论