问题
i need serious help here! i have this site am building: a summary of each article is generated from the database with the title as a link, but i want it to be that if someone clicks on the link, a page of the article is automatically generated without hustling; for i cannot code a page for every article i have in the database! here's my code that generates a summary:
<?php
if(isset($_POST['search'])){
$term = mysql_real_escape_string($_POST['keyword']);
$search = mysql_query("select * from article
where match(title, body) against('$term') ");
if(mysql_num_rows($search)>0){
echo "<div>"."Search Results For: "."<h3><u>".$term."</u></h3>"."</div>";
while($result = mysql_fetch_array($search)){
echo "<div class=\"article\">".
"<div class=\"title\"><a href=\"".$result['cat'].".php"."\">".$result['title']."</a></div>".
"<div class=\"body\">".substr($result['body'], 0, 250)."</div>".
"<div class=\"cat\"><a href=\"".$result['cat'].".php"."\">"."Category: ".$result['cat']."</a></div>".
"<div class=\"author\">"."Author: ".$result['author']."</div>".
"<div class=\"dateTime\">"."Date: ".$result['date']."</div>".
"</div>";
}
}
else{
echo "Sorry! The search for "."<h3>".$term."</h3>"." gave no results.";
}
}
?>
回答1:
Assuming each of the articles has its ID. Change the link to go to a dynamic page, passing that ID:
"<div class=\"title\"><a href=\"dynamic_page.php?id=$result[id]\">$result[title]</a></div>"
Then create a dynamic_page.php that accepts that ID and generates the article as follows:
if (isset($_GET['id'])) {
$id = mysql_real_escape_string($_GET['id']);
$q = "SELECT
*
FROM
`article`
WHERE
`id` = '$id'
LIMIT 1;";
$q = mysql_query($q);
if (mysql_num_rows($q) > 0) {
$result = mysql_fetch_assoc($q);
echo "<div class=\"article\">".
"<div class=\"title\">".$result['title']."</div>".
"<div class=\"body\">".$result['body']."</div>".
"<div class=\"cat\"><a href=\"".$result['cat'].".php"."\">"."Category: ".$result['cat']."</a></div>".
"<div class=\"author\">"."Author: ".$result['author']."</div>".
"<div class=\"dateTime\">"."Date: ".$result['date']."</div>".
"</div>";
}
else {
/* Article not found */
}
}
Note that the $result['body'] is shown in full this time. Also I suggest using mysql_fetch_assoc() in your case.
The code is here
回答2:
If the link is something like page.com/article.php?id=20 then your query would look like the following:
$id = mysql_real_escape_string($_GET['id']);
mysql_query("SELECT * FROM articles WHERE id = '$id'");
Then you can use mysql_fetch_array to display the data.
来源:https://stackoverflow.com/questions/13749042/php-dynamically-generate-new-web-page-from-link