通过id从PHP中删除数据库中的特定条目

时间:2013-11-05 11:21:49

标签: php mysql database

我有一个users.php文件,我存储了所有的功能。我想创建一个删除按钮,以删除某个经理下的任何列出的员工。 这是我对成员函数的看法:

public function view_team($username) {
    $query = $this->db->prepare("SELECT * FROM `users` WHERE `manager`= ? ORDER BY `lastname` ASC ");
    $query->bindValue(1, $username);
    $i = 0;

    try{
            $query->execute();
            foreach ($query as $row) {
                $removable=$row['id'];
                print $i+1 .') '.$row['lastname'].' '.$row['firstname'].', Department: '. $row['department'] .', Band: '.$row['band'].' | '; ?> 
                Promote  <img src="img/promote.png" alt="Promote employee"> | <!-- promote user -->
                Edit  <img src="img/edit.png" alt="Edit employee"> | <!-- edit user -->
                <a href ="#" onclick="$users->remove($removable)">
                Remove <img src="img/remove.png" alt="Remove employee"></a> <!-- remove user -->
                <?php print '<br>';
                $i++;
            }

    $this->queryResult = $query->fetch();

    } catch(PDOException $e){
        die($e->getMessage());
    }
}   

这是删除功能:

public function remove($username) {
    $query=$this->db->prepare("DELETE from `users` WHERE `id`=?"); 
    $query->bindValue(1,$removable);
    try{
        $query->execute();
        } catch (PDOException $e){
        die($e->getMessage());
        }
}

这就是我查看用户的方式:

<?php
$usr = $firstname ." ". $lastname;
$users->view_team($usr);

?>

我想我需要创建一个onclick()函数才能在按下“删除”按钮时起作用。

1 个答案:

答案 0 :(得分:0)

您的删除代码会自动启动,而不是手动启动:

<?php 
                        $removable = $row['id'];
                        $query=$this->db->prepare("DELETE from `users` WHERE `id`=?"); 
                        $query->bindValue(1,$removable);
                        try{
                            $query->execute();
                        } catch (PDOException $e){
                            die($e->getMessage());
                        }
                    ?>

编辑后:

请尝试;

<a href ="#" onclick="$users->remove($removable)" ?> 
"> Remove <img src="img/remove.png" alt="Remove employee"></a>

代替;

<a href =" 
   <?php $removable=$row['id']; $users->remove($removable); ?> 
">Remove <img src="img/remove.png" alt="Remove employee"></a>