2

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.

1

6 Answers 6

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

2 Comments

@OptmiusCrime all suggestions are very good but this is very handy and easy to mantain.. Thanks
@user1765876 - Me, keeping it simple since 2001.
0

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);
}

Comments

0
const DEBUG = true;

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

...

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

1 Comment

use_mysql_query_even_though_it_sucks() haha
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.