Nate
Nate

Reputation: 28384

How to stop database data from breaking an HTML page?

I know that when taking data from a form and putting it into a MySQL database that the data should be escaped using mysql_real_escape_string() to prevent SQL injections. My question is a little different.

I am pulling data from a MySQL database and then displaying it on the page, but I am having a problem. Suppose my data looks like this:

This is some test data, and here's a quote. For good measure, here are "some more" quotes.

Now, my php code would something like this:

echo '<input type="text" value="' . $data . '">';

This results in a broken HTML page, because the data has quotes inside it and it's being displayed inside an input tag that encompasses the data with quotes.

See the problem?

What is the best solution for this?

Upvotes: 0

Views: 257

Answers (3)

Joseph Ledesma Gabito
Joseph Ledesma Gabito

Reputation: 361

You can try the following:

echo '<input type="text" value="' . stripslashes($data) . '">';

Best if you can separate your php code from your html.

<input type="text" value="<?php echo stripslashes($data);?>">

Thanks :)

Upvotes: 1

Not_a_Golfer
Not_a_Golfer

Reputation: 49195

You need to escape the data for html entities:

echo '<input type="text" value="' . htmlentities($data) . '">';

Upvotes: 2

Marc B
Marc B

Reputation: 360682

Just like mysql_real_escape_string() is for SQL operations, on the HTML side of things, it's htmlspecialchars().

Upvotes: 6

Related Questions