Orionis
Orionis

Reputation: 1011

php echo prepend a /r/n to output

Possibly this is another of my silly questions, but...
I have this very simple PHP file which returns from a MySQL DB the very first date within a 'datetime' field of a table:

<?php
$query = "SELECT MIN(Date) FROM Table";
$result = mysqli_query($db,$query); //$db defined elsewhere
if ($result) {
	$row = mysqli_fetch_row($result);
	echo $row[0];
}
?>

Everything is fine, the date is returned, but there is an extra '\r\n' at the beginning; i.e: '\r\n2019-01-21'.

I do not understand where this comes from and it is generating errors in the rest of the program.

Pls note that I currently have several other PHP files that do not manifest this problem.

At the moment I temporary fixed it with a 'firstdate.slice(2)'.

What is wrong?

EDIT
I checked the MySql/PHP side and there is not any extraneus char (thanks to Alister for the var_dump suggestion). I also removed the closing ?> tag, with same result.
It seems that the problem comes from the Ajax call, which follows:

$.ajax({
    url: "php/caricaPrimaData.php", //the above snippet
    type: "GET",
    async: false, //I know, should be True, but it is ok for me
    success: function(response){ //response = '/r/n2015-11-15'
    	gFirstDate = response.trim();
  	}
});

Here the 'response' variable (checked with Mozilla debugger) shows the newline, which is then deleted by trim.
The solution is acceptable, but the curiosity is still here.

Upvotes: 0

Views: 77

Answers (1)

Alister Bulman
Alister Bulman

Reputation: 35149

If the output to screen has the extra newlines, and not the variable (check with var_dump($row[0]);), then if you are including other files ahead of running that code, and the other files also have the close-PHP ?> tags, you may have a blank line hidden after the tag, somewhere among the files.

That is why it has been best practice to no longer use any closing-php tags when they are not required - which would only be in the middle of a HTML file, that has some PHP in there.

Without a closing tag, you can't put anything after it, even accidentally.

Upvotes: 2

Related Questions