我正在製作一個動態網頁,允許用戶發佈他們最喜歡的食譜。在每個食譜下面有一個鏈接,可以讓你對食譜做出評論。如果您發表評論,則評論將被髮布到數據庫中,除非評論中有任何撇號。下面是該addcomment.inc.php頁面的代碼:所謂addcomment.inc.php如何正確處理html表單中的撇號?
<?php
$con = mysql_connect("localhost", "test", "test") or die('Sorry, could not connect to database server');
mysql_select_db("recipe", $con) or die('Sorry, could not connect to database');
$recipeid = $_GET['id'];
$query = "select title from recipes where recipeid = $recipeid";
$result = mysql_query($query) or die('Could not retrieve file: ' . mysql_error());
echo "<form action=\"index.php\" method=\"post\">\n";
if (mysql_num_rows($result) == 0) {
$title = "Unknown Title";
}
else {
while($row=mysql_fetch_array($result, MYSQL_ASSOC)) {
$title = $row['title'];
}
}
echo "<h2>Enter your comment for the recipe \"$title.\" </h2>";
echo "<textarea rows=\"10\" cols=\"50\" name=\"comment\"></textarea><br>\n";
echo "Submitted by:<input type=\"text\" name=\"poster\"><br>\n";
echo "<input type=\"hidden\" name=\"recipeid\" value=\"$recipeid\">\n";
echo "<input type=\"hidden\" name=\"content\" value=\"addcomment\">\n";
echo "<br><input type=\"submit\" value=\"Submit\">\n";
echo "</form>\n";
?>
不同的PHP文件中檢索信息。這是下面的代碼:
<?php
$recipeid = $_POST['recipeid'];
$poster = $_POST['poster'];
$comment = htmlspecialchars($_POST['comment']);
$date = date("Y-m-d");
$con = mysql_connect("localhost", "test", "test") or die('Could not connect to server');
mysql_select_db("recipe", $con) or die('Could not connect to database');
$query = "INSERT INTO comments (recipeid, poster, date, comment) " .
" VALUES ($recipeid, '$poster', '$date', '$comment')";
$result = mysql_query($query) or die('Could not query databse. ' . mysql_error());
if ($result)
echo "<h2>Comment posted</h2>\n";
else
echo "<h2>Sorry, there was a problem posting your comment</h2>\n";
echo "<a href=\"index.php?content=showrecipe&id=$recipeid\">Return to recipe</a>\n";
?>
如何才能使此代碼正確處理單引號如果輸入到註釋表單中?