Reputation: 5596
My code is like this:
<?php
define("ERROR", "SOMETHING WRONG WITH MY DATABASE");
...
if (!mysql_query($q)){
die(ERROR);
}
?>
Now I want to replace "SOMETHING WRONG WITH MY DATABASE" with mysql_error()
in case I want to debug it. what is the easiest way ?
This does not seem to work work: define("ERROR", mysql_error());
---- edit ---
I don't want to use mysql_error() under production environment, it may help the attacker figure out something related to my database? That's my point of using a constant string
as in C you can do
#define x yourfunction()
I'm not sure if I can do the same in php
Upvotes: 0
Views: 3141
Reputation: 791
You can use something like Stefan suggested and add a DEBUG constant which you can switch between prod and dev environment:
define('DEBUG', 1);
// In the function:
// ...
echo ERROR;
if (DEBUG){
echo mysql_error();
}
die();
Upvotes: 0
Reputation: 57306
The simple answer is "you cannot do that". The whole point of constant is that it's constant as in its value is never changed. If it refers to a function call, the function can return any value - and it's not constant any more.
One trick you can do is define the function call itself to be the value of the constant - and then eval
it on demand, something like this:
define("ERROR", "return mysql_error()");
...
die(eval(ERROR));
However this is really a rather bad code. You'd be much better off doing
die(mysql_error());
Upvotes: 3
Reputation: 3900
mysql_error() has to be called AFTER the sql operation that you are trying to catch. You cannot catch this error with a predeclared constant or variable. You either have to call it directly, or call another function which calls it, like so:
die(mysql_error());
or:
define("ERROR", "Database Problem ");
function Err() {
$sql_err = ERROR . mysql_error();
return $sql_err;
}
// sql operation here, then test for error
die(Err());
Upvotes: 1
Reputation: 88647
A constant should be exactly what the name implies - constant. You cannot redeclare a constant, and anything that has a variable value should be stored in - you guessed it - a variable.
However, you could do something like this:
<?php
define("ERROR", "SOMETHING WRONG WITH MY DATABASE: ");
// ...
if (!mysql_query($q)){
die(ERROR . mysql_error());
}
?>
Upvotes: 1