MYSQLi real exit function displaying newlines and carriage returns

I have a text area from which when I try to escape and misinform via the MYSQLi real_escape and nl2br function and just the output gives me odd results.

my PHP code:

 <?php
 $db = new mysqli('localhost', 'user', 'pass', 'demo');

 if($db->connect_errno > 0){
 die('Unable to connect to database [' . $db->connect_error . ']');
 }

 $postText = nl2br($db->escape_string($_POST['posting']));
  ?>

      

the output is odd :

 i love this\r\n\r\nand this is gonna be funn.,

      

and strangely, when I just use nl2br

without real_escape

, it gives a thin output which obviously cannot move forward with user input I can not trust.

Please help with this ..

+3


source to share


2 answers


You should only use SQL escaping when the output will be used in an SQL query.

  • If you need to output a value to a page, you use htmlspecialchars()

    or htmlentities()

    .

  • If it will be used in JavaScript literature, use json_encode()

    .

  • Etc.



In short, each context has its own escaping; don't mix them.

Also, do not use nl2br()

when writing to a database; rather, apply it after retrieving from the database.

+2


source


Yes it is. The output of this function is not intended for printing. But only for formatting string literals. Note that this feature is not intended to "disinfect" any entrance . Please refer here for information

So, you should never use these 2 functions together.



  • use escape_string to format the SQL strings that you intend to dynamically insert into the query.
  • use nl2br only when printing text on HTML page

According to your question in the comments, there shouldn't be a case where you should print your line immediately.
Because after every POST request, your PHP must respond with a header Location:

to tell the browser to reload the page. After such a reboot, you can read data from the database and print it.

0


source







All Articles