0

我知道从表单中获取数据并将其放入 MySQL 数据库时,应该使用 mysql_real_escape_string() 对数据进行转义以防止 SQL 注入。我的问题有点不同。

我正在从 MySQL 数据库中提取数据,然后将其显示在页面上,但我遇到了问题。假设我的数据如下所示:

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

现在,我的 php 代码将是这样的:

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

这会导致 HTML 页面损坏,因为数据在其中包含引号,并且它显示在包含带引号的数据的输入标记内。

看到问题了吗?

什么是最好的解决方案?

4

3 回答 3

6

就像mysql_real_escape_string()SQL 操作一样,在 HTML 方面,它是htmlspecialchars().

于 2012-05-19T18:46:04.790 回答
2

您需要转义 html 实体的数据:

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

于 2012-05-19T18:46:22.943 回答
1

您可以尝试以下方法:

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

如果您可以将 php 代码与 html 分开,则最好。

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

谢谢 :)

于 2012-05-19T18:59:16.720 回答