Hi there,
So I’m having an absolute mare with carriage returns at the moment, and I can’t seem to make any headway.
Very simply I have a form with a textarea. The contents of the textarea is stored into a mysql database. When the data is retrieved, it contains \r
characters within the text, rather than creating new lines.
Here’s the PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$text = mysqli_real_escape_string($link, $_POST['text']);
$sql = "INSERT INTO `t1` SET `text` = '$text'";
if(!mysqli_query($link, $sql){
trigger_error('Unable to add data to database.');
echo mysqli_error($link) . '<br>' . $sql;
}
}
When I come to output the data I’m using markdown to convert preformatted text into nice HTML markup, but alas I get something like this:
Sed posuere consectetur est at lobortis.\\r\
\\r\
Curabitur blandit tempus porttitor.
Rather than:
Sed posuere consectetur est at lobortis.
Curabitur blandit tempus porttitor.
Interestingly if I add double quotes like so:
echo Markdown('"' . $text . '"');
I’ll get this:
<p>"Sed posuere consectetur est at lobortis.</p>
<p>Curabitur blandit tempus porttitor."</p>
Which is good, but obviously I don’t want quote marks in the text.
Any ideas how I can solve this problem?
Cheers,
Mike
Any ideas?
Try this:
echo Markdown(nl2br("$text",true)); // True for XHTML <br /> or false for HTML <br>
http://php.net/manual/en/function.nl2br.php
Thanks for your reply NuttySkunk,
nl2br doesn’t work, because its not seeing the carriage returns. It just sees the characters \r
. In fact Markdown will convert carriage returns into <br> and <p> tags itself anyway.
It’s getting a little frustrating. I’m sure you know that "\r
", will be treated as carriage returns, and '\r
’ will not. It’s as if the data coming from the db is in single quotation marks, and so is actually printing the specials characters. Now, if I just use htmlspecialchars() on the post data, it’s fine, cos nothing is escaped. But that’s a bit weak, since it allows for injection attacks.
It’s weird, cos I have done something like this before in a previous project, and it works fine with mysqli_real_escape_string. I’m wondering if its to do with the table’s default character set or something similar??
Anyways, many thanks,
Mike
Ok, so I worked it out. Well, I got it to work at least.
I changed the sql command in single quotes, and the data in double quotes like so:
$text = mysqli_real_escape_string($_POST['text']);
$sql = 'INSERT INTO `t1` SET `text` = "' . $text . '"';
mysqli_query($link, $sql)
And it seems to do the trick.
I was also using a session to store the data which was adding to the confusion.
Anyways, it’s all sorted now.