PHP不会将html标签插入数据库

时间:2013-12-02 03:40:59

标签: php

PHP不允许我出于某种原因将我的用户名字段插入数据库:

$username = "<a href='user.php?user=".$_SESSION['username']."'>@".$_SESSION['username']."<a>";

/* Query database to save user's post */
/* If field "repostid==0", then the post is not a repost; if the field "repostid>0", then the post is a repost with the field "repostid" linking to the id of the post to be reposted */ 
$result = mysqli_query($connection, "INSERT INTO posts (user, content, repostid, date) VALUES ('$username', '$final_repostinfo', '$_GET[postid]', '$date_string')");
if (!$result)
{
    die('Cannot query. Error: ' . mysqli_error($connection));
}

返回的PHP语法错误:

Cannot query. Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'user.php?user=shawn619'>@shawn619', 'fifth', '8', '01/12/2013 21:38:56')' at line 1

2 个答案:

答案 0 :(得分:1)

您可以通过分隔html标记来解决此问题。 尝试将html标记插入数据库时​​,我遇到了类似的问题。 将$ username保留为$ _SESSION ['username'],然后在需要从数据库中检索值时添加html标记。 例如,我试图通过将标记输入数据库来削减角落,而不是将其放在需要使用的位置。

我有以下PHP代码:

$image = "<img src='".$_FILES['image']['name']."' />";
$query = mysql_query("INSERT INTO news VALUES (CURRENT_DATE,'$image')");

然后在我用来从数据库中检索数据的页面中:

echo $row['images'];

我发现我应该做的是PHP代码:

$image = $_FILES['image']['name'];
$query = mysql_query("INSERT INTO news VALUES (CURRENT_DATE,'$image')");

并将标记放在适当的位置:

echo "<img src='";
echo $row['images'];
echo "' />";

我认为您可以为您的代码实施类似的策略,以解决问题。
注意:mySQL现在已被折旧,但您可以将此技术用于其后续版本,mySQLi和PDO。

答案 1 :(得分:-1)

这是因为单引号。尝试:

$result = mysqli_query($connection, "INSERT INTO posts (user, content, repostid, date) VALUES ('".mysql_real_escape_string($username)."', '$final_repostinfo', '$_GET[postid]', '$date_string')");

或者

$result = mysqli_query($connection, "INSERT INTO posts (user, content, repostid, date) VALUES ('".add_slashes($username)."', '$final_repostinfo', '$_GET[postid]', '$date_string')");