我正在使用 PHP 数组来收集已添加到我的 MySQL 数据库中的用户输入。由于这是来自用户输入的信息,因此我使用数据库中的 num_rows 创建的变量来确定 for 循环通过显示我的数组值运行的次数。for 循环包含一个显示数组的一个值的表单和一个“like”按钮(type=submit),并重复此表单直到显示所有值(从最新到最旧),然后是一个“like”按钮每个。
我希望用户能够单击“喜欢”按钮,为该帖子添加“喜欢”。我遇到的问题是我拥有的代码正在为每个帖子添加一个“喜欢”(因为代码会检查是否按下了“喜欢”按钮,并且由于“喜欢”按钮是由for 循环,每个“喜欢”按钮都具有相同的名称)。我试图通过根据递增变量为“喜欢”按钮命名来纠正此问题,但如果名称是变量或数组,该按钮似乎不起作用。
这是我的代码:
<?php
error_reporting (E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
$userside = $_SESSION['side'];
echo "<b>Organized posts:</br><hr /></b>";
require("./postconnect.php");
$query = mysql_query("SELECT * FROM original ORDER BY postid ASC");
$numrows = mysql_num_rows($query);
$numrows = $numrows-1;
$sql = "SELECT postername FROM original ORDER BY postid ASC"; // select only the postername field from the table "original"
$result = mysql_query($sql); // process the query
$name_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$name_array[] = "".$row['postername'].""; // get the postername field and add to the array above
}
$sql = "SELECT post FROM original ORDER BY postid ASC"; // select only the post field from the table "original"
$result = mysql_query($sql); // process the query
$post_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$post_array[] = "".$row['post'].""; // get the post field and add to the array above
}
$sql = "SELECT posterside FROM original ORDER BY postid ASC"; // select only the posterside field from the table "original"
$result = mysql_query($sql); // process the query
$side_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$side_array[] = "".$row['posterside'].""; // get the posterside field and add to the array above
}
$sql = "SELECT likes FROM original ORDER BY postid ASC"; // select only the likes field from the table "original"
$result = mysql_query($sql); // process the query
$likes_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$likes_array[] = "".$row['likes'].""; // get the likes field and add to the array above
}
$i=$numrows;
for($i;$i>=0;$i--) {
if ($side_array[$i]==1) {
$color="red";
}
elseif ($side_array[$i]==2) {
$color="blue";
}
elseif ($side_array[$i]==3) {
$color="green";
}
echo "<form action='./memberhag.php' method='post'>
<table>
<tr>
<td><font color='$color'>$name_array[$i]</font> - $post_array[$i]</td>
</tr>
<tr>
<td><input type='submit' name='likebtn' value='Like' /> <font color=$color>$name_array[$i]</font> has $likes_array[$i] likes!</td>
</tr>
</table>
</form>";
if ($_POST['likebtn']) {
$numlikes = $likes_array[$i];
$numlikes = $numlikes + 1;
mysql_query("UPDATE original SET likes = '$numlikes' WHERE postername = '$name_array[$i]'");
}
}
?>
这让我困惑了好一阵子……我什至尝试过使用 while 循环而不是 for 循环。