Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a line number in a PHP script

Tags:

php

debugging

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.

like image 983
Kris_R Avatar asked Mar 28 '13 14:03

Kris_R


People also ask

How to get current line number in php?

You can use the magic constant __LINE__ for this. will show the line number where that statement is in the file.

How can I get line by line code in PHP?

Yes, you can step line by line using Xdebug. Just use editor/IDE that supports Xdebug (PhpStorm/NetBeans/VSCode/etc). For example, for PhpStorm check these links: jetbrains.com/phpstorm/documentation/debugging and jetbrains.com/help/phpstorm/… thank you, for vscode,can i get that?

Does \n work in PHP?

Answer: Use the Newline Characters ' \n ' or ' \r\n ' You can use the PHP newline characters \n or \r\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string.


3 Answers

You can use the magic constant __LINE__ for this.

echo  __LINE__;

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

like image 170
Dan Avatar answered Oct 19 '22 09:10

Dan


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__)

like image 24
internals-in Avatar answered Oct 19 '22 09:10

internals-in


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.

like image 1
janisch Avatar answered Oct 19 '22 09:10

janisch