I have a form where users can enter anything, for instance, suppose a user entered:
Hello World!
This is a new line.
This was written after two new lines.
The data that user submits using the form is inserted in DB:
$data = mysqli_real_escape_string($dbc, $_POST['text']);
$sql = "INSERT INTO data (Data) VALUES ('$data')";
$exec = mysqli_query($dbc, $sql);
Now it gets stored in database but when I fetch the text from the DB to show to the user, it displays:
Hello World! This is a new line. This was written after two new lines.
As you can see, the new lines are ignored. I also want to show line breaks.
I tried:
$data = mysqli_real_escape_string($dbc, str_replace('\n', '<br>', $_POST['text']));
but that doesn't work either. How can I show line breaks when displaying data from mysql?
It is best to put your user input into the database unaltered (except for escaping, of course) in case you wish to query against the user input, or change your display behavior later on. That said, upon building your page and displaying the data, use
echo nl2br(htmlspecialchars($row['text'], ENT_QUOTES));
nl2br() converts all the "\r\n" or "\n" to <br /> so that it displays nicely. htmlspecialchars() converts any special characters the user typed into the field originally to proper html escape sequences.
Your code would work, except your \n should be wrapped in double quotes instead of single quotes. Single-quoted strings ignore escape sequences in PHP. However, as shown, a built-in function already exists for accomplishing this.
I believe you want nl2br. http://php.net/manual/en/function.nl2br.php The str_replace won't work because you'd need the \n in double quotes. As is you are searching for a literal '\n'.
$data = mysqli_real_escape_string($dbc, nl2br($_POST['text']));
Related
I have some php script that is adding a new line to a string saved in MYSQL in a mychar field.
When I look at the database using mysqladmin, I can see fields that have multiple lines. They do not show any characters. Whatever is creating the new line is invisible.
However, when I try to update an existing string with a string that includes an extra line, using \n, it updates the field as empty. I'm guessing this is because mysql does not accept \n in an update statement.
Can anyone suggest how to prepare a string in PHP so that when updating a field in MYSQL it updates properly, ie with new line. \n does not seem to work.
$sql = "UPDATE comments SET comment = 'firstline\nsecondline\nthirdline' WHERE id = 23"
When you run the above statement, it does update the line but the comment field is empty.
Thanks for any suggestions.
The statement is parsed 2 times: First by PHP and then my MySQL.
PHP replaces \n with the line feed character, but MySQL seems to ignore those whitespace characters. By double escaping \n to \\n you achieve, that the \n character sequences are parsed by MySQL and inserted as line feeds.
Hi you can try like this
$data = 'firstline\nsecondline\nthirdline';
$sql = "UPDATE comments SET comment = $data WHERE id = 23"
This is probably really stupid, but I try to save content from a texarea into MySQL with PHP. Normally newlines are preserved in the database. But suddenly they are removed.
I use jquery to send the values to PHP with ajax, and then I do this in PHP:
$var = strip_tags( $_POST["var"] );
$db->query("UPDATE table SET var='$var' WHERE id=$id")
Somehow newlines are lost on the way in. If I do nl2br on the var, then they are translated to <br/>, so $var contains newline right up until I run the query.
Update, to add to the strangeness. If I actually run nl2br on $var, and then replace br-tags with newline, before updating the table, all is well, what is going on?!?
This is working just fine:
$var = strip_tags( $_POST["var"] );
$var = nl2br($var);
$var = preg_replace('#<br\s*/?>#i', "\n", $var);
$db->query("UPDATE table SET var='$var' WHERE id=$id");
I've had another look into the Zebra (source code this time), and as mentioned in previous comment this is exactly why newlines get removed. The escape method from Zebra package uses:
http://php.net/manual/en/mysqli.real-escape-string.php
which means the following are removed:
NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
You could try to add the input in:
<pre></pre>
This will save your input as preformatted text in the database.
Reference: https://www.w3.org/wiki/HTML/Elements/pre
nl2br is a good solution too, use whichever you prefer.
Also make sure you are using the right configuration for your database column. It should be VARCHAR or TEXT.
I think your problem is that newlines get removed before being passed to the server.
You mentioned it's being sent with jQuery so make sure there isn't any client-side processing before being sent to the server.
I used textarea to upload the user discription into the database of phpmyadmin. User can use any characters and spaces, new line, and other special characters. When I retrive the infomation from the database its showing all in one para with no formatted text. I want the text to appear the same as the user inserted like how its appearing in the forums. Below are the codes I used....
Input html
<textarea class="noticearea" name="notice_area" id="notice_area" required="required"><?php echo htmlspecialchars($_POST["notice_area"]); ?></textarea>
php read
$notice_area = mysql_real_escape_string($_POST["notice_area"]);
SQL insert
$noticeinsert = mysql_query("INSERT INTO notice (notice_area) VALUES ('$notice_area')");
retrive infomration
<?php echo htmlspecialchars($notice_area); ?>
Everything is fine no error or warning. I can retrive easily but not in a format. Please suggest me if i have to add any code.
You might need the following code for displaying.
// $notice_area assumes you have database query and the reuslt is correctly fetched.
echo str_replace("\\r\\n","<br/>", (htmlspecialchars(($notice_area))));
Why?
http://php.net/manual/en/function.mysql-real-escape-string.php
mysql_real_escape_string() will add slashes prior to \n , \r, so on.
after inserting into db then are then \n \r in plain text because you added them by \\n and \\r.
so after getting the plain text of \n and \r, you need to replace them with , then it is it :D
I have built a search engine using php and mysql.
Problem:
When I submit a word with an apostrophe in it and return the value to the text field using $_GET the apostrophe has been replaced with a backslash and all characters after the apostrophe are missing.
Example:
Submitted Words: Just can't get enough
Returned Value (Using $_GET): Just can\
Also the url comes up like this:search=just+can%27t+get+enough
As you can see the ' has been replaced with a \ and get enough is missing.
Question:
Does anybody know what causes this to happen and what is the solution to fix this problem?
The code:
http://tinypaste.com/11d62
If you're running PHP version less than 5.3.0, the slash might be added by the Magic Quotes which you can turn off in the .ini file.
From your description of "value to the text field" I speculate you have some output code like this:
Redisplay
<input value='<?=$_GET['search']?>'>
In that case the contained single quote will terminate the html attribute. And anything behind the single quote is simply garbage to the browser. In this case applying htmlspecialchars to the output helps.
(The backslash is likely due to magic_quotes or mysql_*_escape before outputting the text. I doubt the question describes a database error here.)
Update: It seems it's indeed an output problem here:
echo "<a href='searchmusic.php?search=$search&s=$next'>Next</a>";
Regardless of if you use single or double quotes you would need:
echo "<a href='searchmusic.php?search="
. htmlspecialchars(stripslashes($search))
. "&s=$next'>Next</a>";
(Notice that using stripslashes is a workaround here. You should preserve the original search text, or disable the magic_quotes rather.)
Okay I forgot something crucial. htmlspecialchars needs the ENT_QUOTES parameter - always, and in your case particularly:
// prepare for later output:
$search = $_GET['search'];
$html_search = htmlspecialchars(stripslashes($search), ENT_QUOTES);
And then use that whereever you wanted to display $search before:
echo "<a href='searchmusic.php?search=$html_search&s=$next'>Next</a>";
Single quotes are important in PHP and MySQL.
A single quote is a delimeter for a string in PHP, for example:
$str = 'my string';
If you want to include a literal quote inside a string you must tell PHP that the quote is not the end of the string. It is escaped with the backslash, for example:
$str = 'my string with a quote \' inside it';
See PHP Strings for more on this.
MySQL operates in a similar way. An example query might be:
$username = 'andyb';
$quert = "SELECT * FROM users WHERE user_name = '$username'";
The single quote delimits the string parameter. If the $username included a single quote, this would cause the query to end prematurely. Correctly escaping parameters is an important concept to be familiar with as it is one attack vector for breaking into a database - see SQL Injection for more information.
One way to handle this escaping is with mysql_real_escape_string().
I am retrieving a product description value stored in database from admin through textarea upon form submit. When I select the description from database I get $description = $row['description']; and I would like to echo $description on main page like this: echo nl2br($description); but I see "\r\n" characters instead of making new rows. From what I've found here and on the net, your string must be used between double quotes, like this:
echo nl2br("Hello, \r\n This is the description");
Now, the value of $description from database is in fact "Hello, \r\n This is the description" but in my script I have to use it like this:
echo nl2br($description);
Which does not make br's, it is outputing \r\n instead. So, what can I do, I can't use double quotes here, from my experience.
You could translate them into their respective escape sequences before passing the string through nl2br(), like this:
$description = nl2br(str_replace('\\r\\n', "\r\n", $description));
But what are the literal escapes doing in your database in the first place?
You are storing the literal value of \r\n in your database, not the actual characters they represent.
Verify this in your database. If you see \r\n in the description field, then you're probably escaping the backslash when you're storing the data.
It looks like your text contains the individual characters \, r, \, and n, and does not contain actual newline characters. As such, str_replace() should get the job done:
echo str_replace('\r\n', '<br>', $description);
The nl2br can take a second (optional) argument for "is_xhtml" which will convert the \r\n into a <br> for you. Just change your line to:
echo nl2br($description, TRUE);