1

I'm working on a simple messaging web. The process is simple, I enter the text with line breaks and it will be saved on the database and display it in another div. Everything was fine until I used mysqli_real_escape_string() which removed all the line breaks and display whole text in a single line

$text = $_POST['new_text'];

$vaild_text = mysqli_real_escape_string($con,trim($text));
$vaild_text = strip_tags($vaild_text);  

$breaked_text = nl2br($vaild_text);   

$command = "INSERT INTO textTable (text_col)VALUES ('$breaked_text')";    
$query = mysqli_query($con,$command);

If I remove mysqli_real_escape_string() everything works very well but for the matter of security I Can't

I even changed the nl2br() position and put it after and before mysqli_real_escape_string() but it didn't work!

Nasser Ali Karimi
  • 4,462
  • 6
  • 34
  • 77
reza hooshyarr
  • 107
  • 1
  • 5

2 Answers2

2

The safest way is to use Prepared Statements:

// Strip the tags and convert the newlines to line breaks
$text = strip_tags($_POST['new_text']);   
$breaked_text = nl2br($text);

// Prepare the query
$statement = $con->prepare("INSERT INTO textTable (text_col) VALUES (?);");
$statement->bind_param("s", $breaked_text); // The "s" stands for Strings

// Execute the SQL query
$statement->execute();

Using Prepared Statements has a few benefits:

  1. It prevents SQL injections by escaping the parameters.
  2. It's faster if you want to execute the query multiple times, because the query is prepared only once.
  3. No need to concatenate the values into the query. Of course, the sprintf() function could be an alternative for concatenating a string when not using prepared statements. I do recommend prepared statements though.

You can find more benefits and examples about Prepared Statements in this answer: https://stackoverflow.com/a/5662391/3625118

More information about the bind_param() function can be found here.

Matthijs
  • 2,483
  • 5
  • 22
  • 33
0

I just found the solution all I need to use id nl2br() for displaying the text

$data = mysqli_fetch_assoc($quert);
$text = $data['text_col'];
$text_break_line = nl2br($text);
echo "<p>'$text_break_line'</p>";
reza hooshyarr
  • 107
  • 1
  • 5
  • I'd still recommend using _Prepared Statements_ for safety purposes (and because it's easier to manage) – Matthijs Oct 13 '18 at 10:02