drlh197610 2013-01-03 23:09
浏览 35
已采纳

从表中删除错误的记录

I need your advice. I fetch data from database to table: ID, Name. In table are Actions: Delete, Enable, Block. When action Delete is selected, I would like, that respectively record will be deleted. However, my script does not work and always delete last record, even I select another record. I think problem is, that select name and hidden input name is similar for all records. But I can not find way, how to create them with different names. Any advice is welcome.

HTML:

  <form method='post'> 
  <table border='1'>
  <tr>
  <th> ID </th>
<th> Name </th>
<th> Action </th>
</tr>

Code:

$db = new PDO('mysql:host=localhost;dbname=****;charset=utf8', '**', '**');
$query = $db->query("SELECT ID,statusas,login,vardas,email FROM users");

while($row = $query->fetch(PDO::FETCH_BOTH)) { 
 echo "<tr><input type='hidden' name='id' value='".$row[0]."'>";
 echo "<td>".$row[0]."</td>";
 //echo "<td>".$row[1]."</td>";
 echo "<td>".$row[2]."</td>";
 //echo "<td>".$row[3]."</td>";
// echo "<td>".$row[4]."</td>";
 echo "<td><select name='action'>
             <option value='choose'>Choose..</option>
             <option value='delete'> Delete </option>
             <option value='enable'> Enable </option>
             <option value='block'> Block</option>
        </select></td>";
   echo "</tr>";
 }
 echo "<br><input type='submit' name='submit'></table></form>";

 if($_POST['submit']) {
   if ($_POST['action']== 'delete') {
   echo $_POST['id']; // delete query, but now I am just checking if I get a proper ID.
  }
}
else {
echo "bad";
}

Table

  • 写回答

2条回答 默认 最新

  • doukong9316 2013-01-03 23:19
    关注

    You are using the same name attribute on every row in the form, so they are being overridden and it's using the last one.

    What you could do is either wrap every row in its own form, or you could do something like this, and have only 1 submit button to execute the action on every row:

    // remove hidden id element
    
    ...
    
    echo "<td><select name='action[" . $row[0] . "]'>"
    
    ...
    // remove submit button in the loop, but add it after the while loop
    ...
    
    if (isset($_POST['action']))
    {
        foreach ($_POST['action'] as $id => $action)
        {
            if ($action !== 'choose')
            {
                // do action on the id;
                echo $id . " -> " . $action . "<br>";
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。