使用PHP中的复选框删除MySQL记录

时间:2014-06-15 15:16:02

标签: php mysql checkbox foreach sql-delete

我试图使用复选框删除PHP中的MySQL记录。我回应了每一行,一切似乎都很好。变量和数组的值和格式是正确的。

但是当我尝试使用$delete回显DELETEVAR_DUMP()查询)时,会显示bool(false)(这意味着它无法获得传递给它的变量$emailID的值,对吗?)。为什么呢?

if (isset($_POST['deleteUser']) && isset($_POST['marked_user']))
{

    $marked_user = $_POST['marked_user'];


    foreach($marked_user as $user => $emailID)
    {
        $emailID = (int)$emailID;
        $delete = $base -> query( "DELETE FROM tickets.allowed_users WHERE allowed_users.emailID = '$emailID'");

    }
        header('Location: viewTickets.php?viewType=U');
}

这是来自单独的PHP文件的HTML部分:

echo "<form action='addUser.php' method='POST'><table class='results3' align='center' cellspacing='0'>
            <tr><th class='head' id='headleft'  width='10%'></th>
                <th class='head' id='headright' colspan='4'>E-mail</th></tr>";

            while( $row = mysqli_fetch_array($sql) )
            {
                $email = $row['email'];
                $emailID = $row['emailID'];
                echo "<tr><td width='1%' class='results'><input type='checkbox' name='marked_user[]' value='$emailID'></td>
                        <td class='results' colspan='4'>" . $row['email']."</td></tr>";
            }
                echo "<td colspan='3'><input type='submit' class='button' name='deleteUser' value='Delete'></td></form>";

这是我的表:

CREATE TABLE allowed_Users
(
 emailID INT UNSIGNED NOT NULL AUTO_INCREMENT,
 email VARCHAR(50) NOT NULL,
 PRIMARY KEY( emailID )
);

4 个答案:

答案 0 :(得分:0)

我认为你需要连接一个这样的字符串:

foreach($marked_user as $user => $emailID)
    {
        $emailID = (int)$emailID;
        $delete = $base -> query( "DELETE FROM tickets.allowed_users WHERE allowed_users.emailID = " . $emailID);

    }

答案 1 :(得分:0)

for ($i = 0; $i < count($_POST["marked_user"]); $i++) {
 $base -> query("DELETE FROM tickets.allowed_users WHERE allowed_users.emailID = '".$_POST["marked_user"][$i]."'");
}

检查是否有效。如果是这样,请操纵输入数据,这样您的代码就不会受到SQL注入的攻击。<​​/ p>

答案 2 :(得分:0)

更改此代码

$delete = $base -> query( "DELETE FROM tickets.allowed_users WHERE allowed_users.emailID  = '$emailID'"); 

$delete = $base->query( "DELETE FROM tickets.allowed_users WHERE allowed_users.emailID = '$emailID'");

答案 3 :(得分:0)

我无法让foreach工作,所以我使用了for循环。所以那里。我想我可以更多地依赖for循环。

if(isset($_POST['delete']))
{       
    for($i=0;$i<count($_POST['marked']);$i++)
    {
        $del_id=$_POST['marked'][$i];
        $delete = $base -> query( "DELETE FROM allowed_users WHERE emailID = '$del_id'");   
    }
    header('Location: viewTickets.php?viewType=U');
}