This is my php code:
//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();
It works perfect for most of the queries.It fails when the $head_title has a single or double quotes.I tried using addslashes in news.php but it doesn’t work.
The code fails when the $head_title is something like “America’s Freedom”.In this case $title becomes “America” and the rest of the string gets truncated automatically.So the url becomes something like “localhost/?title=America” instead of “localhost?title=America’s Freedom”.The data type used in mysql is text.The code works perfect for all queries without single or double quotes.
For the URL, URL-encode the value. For putting that encoded URL into HTML, HTML escape it on top:
See The Great Escapism (Or: What You Need To Know To Work With Text Within Text).