问题是while循环总是显示最后插入行的结果。我已经尝试了下面的代码跟随/取消跟随按钮选项。例如,我是一个用户id=1。我已经跟踪了用户id=4。现在,我想遵循userid =5。当我点击跟随按钮(id=5),它变成Unfollow正确。但是,我已经遵循了用户id=4。这就变成了Follow。这是我的问题。
然后我尝试了echo $following;
。它打印5555。这意味着最后插入的数据。但我想要45。我确定我在while循环中犯了一个错误。但我不知道我应该改变什么?
<?php
try
{
$stmt = $conn->prepare("SELECT * FROM users ORDER BY Autoid");
$stmt->errorInfo();
$stmt->execute();
$sth = $conn->prepare("SELECT * FROM followers ORDER BY Autoid");
$sth->errorInfo();
$sth->execute();
while($follow_row = $sth->fetch(PDO::FETCH_ASSOC))
{
$following = $follow_row['Following'];
$follower = $follow_row['Follower'];
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td>". $row['Autoid'] ."</td>";
echo "<td>". $row['Name'] ."</td>";
// echo $row['Following'];
if($_SESSION['sesuname'] == $row['Username'])
{
echo "<td class='itsyou' >Its You ". $_SESSION['sesuname'] ."</td>";
}
else
{
if(($follower == $_SESSION['sesid']) AND ($following != $row['Autoid']))
{
//echo "<td>true</td>";
echo $following;
echo "<td>";
echo "<form id='jsform' method='post' action='subscribe.php'>";
echo "<input type='hidden' name='id' value=" . $row['Autoid'] . " />";
echo "<button class='follow' >Follow</button>";
echo "</form>";
echo "</td>";
}
else
{
//echo "<td>false</td>";
echo "<td>";
echo "<form id='ufform' method='post' action='unsubscribe.php'>";
echo "<input type='hidden' name='uid' value=" . $row['Autoid'] . " />";
echo "<button class='follow' >UnFollow</button>";
echo "</form>";
echo "</td>";
}
}
echo "</tr>";
}
} catch (PDOException $e) {
'Database Error : ' .$e->getMessage();
}
?>
代码:
while($follow_row = $sth->fetch(PDO::FETCH_ASSOC))
{
$following = $follow_row['Following'];
$follower = $follow_row['Follower'];
}
简单地覆盖$following
和$follower
每次获取一行,留下LAST行在变量中获取。也许你想要更像
$following[] = $follow_row['Following'];
$follower[] = $follow_row['Follower'];
^^--- append new row value to an array.