$connect = mysql_connect("localhost", "username", "password");
if($connect) {
mysql_selectdb('phplogin');
$query = mysql_query("SELECT * FROM forum ORDER BY time desc");
$query2 = mysql_query("SELECT * FROM forum");
$data2 = mysql_fetch_array($query2);
$id = $data2['id'];
while($data = mysql_fetch_array($query)) {
echo "<div class='post'>" . "<div class='leftside'>" . "<h3 class='by'>" . $data['user'] . "</h3>" . "<h5 class='date'>" . $data['time'] . "</h5>" . "</div>" . "<div class='after'>" . "</div>" . "<div class='rightside'>" . "<h2 class='title'>" . "<a href='Forum.php?$id'>" . htmlspecialchars($data['title']) . "</a>" . "</h2>" . "<p class='description'>" . htmlspecialchars($data['description']) . "</p>" . "</div>" . "<div class='clear'>" . "</div>" . "</div>";
}
这是我尝试过但它将所有链接的第一行ID分配给我并且我不知道该怎么做,我是php和mysql的新手,感谢您的帮助。
答案 0 :(得分:1)
问题是您要将$id
中的ID保存为变量。这只能容纳一个值。
你为什么这样做?您的查询都是从forum
中选择的,您是否可以使用$data['id']
?
while($data = mysql_fetch_array($query)) {
echo "<div class='post'>" . "<div class='leftside'>" . "<h3 class='by'>" . $data['user'] . "</h3>" . "<h5 class='date'>" . $data['time'] . "</h5>" . "</div>" . "<div class='after'>" . "</div>" . "<div class='rightside'>" . "<h2 class='title'>" . "<a href='Forum.php?".$data['id']."'>" . htmlspecialchars($data['title']) . "</a>" . "</h2>" . "<p class='description'>" . htmlspecialchars($data['description']) . "</p>" . "</div>" . "<div class='clear'>" . "</div>" . "</div>";
}
请注意,mysql_*
函数为officially deprecated,因此不应在新代码中使用。您可以使用PDO或MySQLi。有关详细信息,请参阅this answer on SO。
使用MySQLi和printf()
执行此操作可能如下所示。
$link = mysqli_connect("localhost", "username", "password", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = mysql_query("SELECT * FROM forum ORDER BY time desc");
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($data = mysqli_fetch_assoc($result)) {
printf ("<div class='post'><div class='leftside'>
<h3 class='by'>%s</h3>
<h5 class='date'>%s</h5></div><div class='after'></div><div class='rightside'>
<h2 class='title'><a href='Forum.php?%u'>%s</a></h2>
<p class='description'>%s</p></div><div class='clear'></div></div>",
$data['user'],
$data['time'],
$data['id'],
htmlspecialchars($data['title']),
htmlspecialchars($data['description']));
}
/* free result set */
mysqli_free_result($result);
}