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.
You can use the magic constant __LINE__ for this. will show the line number where that statement is in the file.
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?
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.
You can use the magic constant __LINE__
for this.
echo __LINE__;
will show the line number where that statement is in the file.
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__
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With