53

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

132

You can use the magic constant __LINE__ for this.

echo  __LINE__;

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot -- it led me directly to some other nice constants.
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__)

Comments

1

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.