我是PHP新手,我正在寻找一种方法来区分如何使用循环语句创建的按钮。我的任务是这样的:表格中的每个数据都会显示出来,每个数据的相应更新按钮都会循环显示。如果单击更新按钮,则将更新数据。
这是我的代码:
<?php
$query=mysqli_query($con,"SELECT * FROM POSTS where `post_status`= 1 order by `post_date` DESC");
while($data = mysqli_fetch_array($query))
{
$ID=$data['post_id'];
echo"<tr>";
echo"<td>".$ID ."</td>";
echo"</tr>";
echo"<tr>";
echo"<td>"."on ".$data['post_date'] ."</td>";
echo"</tr>";
echo"<tr>";
echo"<td>".$data['post_title']."</td>";
echo"</tr>";
echo"<tr>";
echo"<td>" .htmlspecialchars_decode($data['post_body'])."<br/>"."</td>";
echo"</tr>";
echo"<tr>";
echo"<td rowspan=1>"."<input type=\"submit\" value=\"Approve\" name=\"$ID\">"."</td>";
echo"</tr>";
echo "<tr>";
echo "<td colspan=4>"."<hr/>"."</td>";
echo"</tr>";
if(isset($_POST['Approve']))
{
$a=$ID;
$query2 = mysqli_query($con, "UPDATE POSTS SET post_status = '2' WHERE post_id='$a'");
}
}
?>
抱歉我的编程技巧不好。希望你能帮助我们。谢谢!
答案 0 :(得分:1)
因为你需要在循环中进行var验证。
哦,并且使用filter_has_var而不是isset,并且如果可能的话,只让php执行php的东西。
为什么要使用filter_ *而不是isset()?因为What is the benefit of using filter_has_var() over isset()
<?php
$query=mysqli_query($con,"SELECT * FROM POSTS where `post_status`= 1 order by `post_date` DESC");
while($data = mysqli_fetch_array($query))
{
$ID=$data['post_id'];
?>
<tr><td><?php echo $ID; ?></td></tr>
<tr><td>on <?php echo $data['post_date']; ?></td></tr>
<tr><td><?php echo $data['post_title']; ?></td></tr>
<tr><td><?php echo htmlspecialchars_decode($data['post_body']); ?><br/></td>
</tr>
<?php // and so on..
echo"<tr>";
echo"<td rowspan=1>"."<input type=\"submit\" value=\"Approve\" name=\"$ID\">"."</td>";
echo"</tr>";
?>
<tr><td colspan=4>.<hr/>.</td></tr>
<?php
}
if(filter_has_var(INPUT_POST,'Approve')) {
$a=$ID;
$query2 = mysqli_query($con, "UPDATE POSTS SET post_status = '2' WHERE post_id='$a'");
}
?>
答案 1 :(得分:1)
你可以使用button
html:
while($data = mysqli_fetch_array($query)) {
....
echo '<button type="submit" name="btn_update" value="'. $ID. '">Update</button>';
}
这样,需要更新的行的id将在$_POST['btn_update']
;
不要忘记验证已发布的ID
答案 2 :(得分:1)
如果我是你,我将使用这样的get方法执行此操作:
<?php
$query=mysqli_query($con,"SELECT * FROM POSTS where `post_status`= 1 order by `post_date` DESC");
while($data = mysqli_fetch_array($query))
{
$ID=$data['post_id'];
echo"<tr>";
echo"<td>".$ID ."</td>";
echo"</tr>";
echo"<tr>";
echo"<td>"."on ".$data['post_date'] ."</td>";
echo"</tr>";
echo"<tr>";
echo"<td>".$data['post_title']."</td>";
echo"</tr>";
echo"<tr>";
echo"<td>" .htmlspecialchars_decode($data['post_body'])."<br/>"."</td>";
echo"</tr>";
echo"<tr>";
echo"<td rowspan=1>"."<a href=\"your current page url?action=update&id=".$ID."\">Approve</a>"."</td>";
echo"</tr>";
echo "<tr>";
echo "<td colspan=4>"."<hr/>"."</td>";
echo"</tr>";
}
?>
然后在页面顶部放置此代码:
<?php
if(isset($_GET['action']) && $_GET['action']==update){
if(isset$_GET['id']){
$a=$_GET['id'];
$query2 = mysqli_query($con, "UPDATE POSTS SET post_status = '2' WHERE post_id='$a'");
}
}
?>