I have couple of mysql queries in PHP and at the end of each query I did this

mysql_query(STRING) or die(mysql_error());

This is fine as far as I am in DEV environment but I dont want production users to see these errors. Any good Idea to remove this messages by just setting ON OFF.

有帮助吗?

解决方案 3

Even easier you could just replace all die( with error_handle( or something else, and include this function:

function error_handle($err) {
    die($err); // Comment this line out if you don't want the error to be displayed.
}

This is also great because you could extend the code to log errors etc in production. You could in addition define a $debug-variable somewhere in your global code if you are using Git or other version-control-systems.

Edit: I suggest replace all die( and not just die to avoid replaces where you don't want it, if you e.g use die in a sentence or something.

其他提示

Apart from the fact that you shouldn't use mysql_ as they're deprecated, you can simply make another function:

define('DEV', true);

function mysql_query_custom() {
    $result = call_user_func_array('mysql_query', func_get_args());

    if ($result === false) {
        if (DEV) {
            die(mysql_error());
        }
    }

    return $result;
}

mysql_query_custom(STRING);

Lots of ways to do it. The most terse and most like you're doing now:

// do this once
$PRODUCTION = true;

// now use
mysql_query() or ($PRODUCTION ?: die(mysql_error()));

I caution though this is not a maintainable way to debug in the long term. There's a lot of good alternatives in this thread.

Whatever you do, develop a comprehensive error detection, logging, and response mechanism in your code. If you're using a framework, leverage its facilities.

Then set a configuration variable called $DEBUG and just wrap your logic in a conditional if/else?

$DEBUG = true;

if ($DEBUG) {
  mysql_query(STRING) or die(mysql_error());
}
else {
  mysql_query(STRING);
}
const DEBUG = true;

function fail($message) { die (DEBUG ? $message : ''); }

...

use_mysql_query_even_though_it_sucks() or fail(mysql_error());
// seriously.  Use mysqli.

Better still, use something like this:

if($_SERVER['SERVER_NAME'] != "dev.mydomain.com"){
    ini_set("display_errors",0);
    ini_set("log_errors", 1);
}

It saves you having to remember to disable the errors when you upload it to the production server.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top