50

Is it possible for a PHP script to return a line number in which some command is called? I'm having trouble describing what I want so maybe an example.

I have PHP code that calls MySQL on many occasions. In line 49 is:

$resultDevice = mysql_query("Some SQL;") or die ("MySQL-Error in settingsU line 49: " . mysql_error());

The text "line 49" I wrote manually. Is it possible to get this number "49" updated if I change my code? It would make my life easier to debug. Of course I can put some other line-specific text into die, but lines are much easier to find in a text-editor.

0

3 Answers 3

125

You can use the magic constant __LINE__ for this.

echo  __LINE__;

will show the line number where that statement is in the file.

1
  • 2
    thanks a lot -- it led me directly to some other nice constants.
    – Kris_R
    Mar 28, 2013 at 20:09
10

if you want a trace you can use(For PHP 4 >= 4.3.0:)

function error_report_function($error) 
{
$dbgt=debug_backtrace();
return "$error in {$dbgt[1][file]} on line {$dbgt[1][line]}";
}

You can use debug_backtrace for this or else always pass the line (with __LINE__)

0
2

You could use something like this:

function throwSQLError($file, $line, $error) {
    return "MySQL-Error in " . $file . " on line " . $line . ": " . $error;
}
$result = mysql_query("Some SQL;") or die (throwSQLError(__FILE__, __LINE__, mysql_error()));

This gives you a dynamic function to throw the error you can use multiple times.

Untested, just written in raw editor.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.