Reputation: 107
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!
Upvotes: 1
Views: 1449
Reputation: 107
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>";
Upvotes: 0
Reputation: 2516
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:
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.
Upvotes: 2