gpt4 book ai didi

php - 如何检索每一行的 ID,然后将其分配给链接

转载 作者:行者123 更新时间:2023-11-29 00:17:06 24 4
gpt4 key购买 nike

$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 的新手,感谢您提前提供帮助。

最佳答案

问题是您将 id 保存在 $id - 一个变量中。这只能包含一个值。

你为什么要这样做?您的两个查询都是从论坛中选择的,您不能使用$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);
}

关于php - 如何检索每一行的 ID,然后将其分配给链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22590908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com