这是我的PHP代码:
//Code for fetching content (view-me.php)
<?php
include('connect.php');
$head_title=$_GET['title'];
//echo $head_title;
$head_title=$mysqli->real_escape_string($head_title);
//echo $head_title;
$query="select title,content,pub_date from news where title='$head_title'";
$result=$mysqli->query($query);
if($result){
while(list($title,$content,$date)=$result->fetch_row())
{
echo '<div id="post_my_head">';
echo "<h1>".$title."</h1></div><br />";
echo '<div id="posted_date_time">'.$date.'</div>';
echo '<div id="post_my_content"><p>'.$content.'</p></div>';
}
$mysqli->close();
}
else
{
echo "Query failed";
}
?>
//Code for printing content:(news.php)
function print_content()
{
include('connect.php');
$query="select title,content,url,pub_date from news order by pub_date desc";
$result=$mysqli->query($query);
while(list($title,$content,$url,$date)=$result->fetch_row())
{
echo '<div id="post_my_head">';
echo "<h1><a href='view-me.php?title=".addslashes($title)."' id='my_post_link'>".$title."</a></h1></div><br />";
//$new_title=str_replace(" ","-",$title);
//echo "localhost/".$new_title."/";
echo '<div id="posted_date_time">Published:'.$date.'</div><br /><br />';
echo '<div id="post_my_content"><p>'.$content.'</p></div>';
}
$mysqli->close();
}
print_content();
它适用于大多数查询。当$ head_title有单引号或双引号时它会失败。我尝试在news.php中使用addslashes但它不起作用。
当$ head_title类似于“America's Freedom”时代码失败。在这种情况下,$ title变为“America”,其余字符串自动截断。所以url变成类似“localhost /?title = America”的东西“而不是”localhost?title = America's Freedom“。在mysql中使用的数据类型是text。该代码适用于没有单引号或双引号的所有查询。
答案 0 :(得分:1)
您可以使用urlencode()和urldecode来解决此问题
答案 1 :(得分:1)
对于URL,对值进行URL编码。为了将编码的URL放入HTML中,HTML将其转移到顶部:
printf('<h1><a href="view-me.php?title=%s" id="my_post_link">%s</a></h1>',
htmlspecialchars(urlencode($title)),
htmlspecialchars($title));
请参阅The Great Escapism (Or: What You Need To Know To Work With Text Within Text)。
答案 2 :(得分:0)
<?php
$str = "Jane & 'Tarzan'";
echo htmlentities($str, ENT_COMPAT);
echo "<br />";
echo htmlentities($str, ENT_QUOTES);
echo "<br />";
echo htmlentities($str);
?>
尝试htmlentities