提交按钮后删除

时间:2014-12-08 11:39:26

标签: php mysql pdo

我有一个表单,当我删除某些产品时,也删除文件夹中的图像。到现在为止还挺好。当我点击按钮Delete时,我会在面板中要求我确认或取消。问题是当我第一次点击Delete时会发生实际删除,那么如果我confirmcancel则无关紧要。 这是delete.php文件

<?php        
error_reporting(E_ALL); 
ini_set('display_errors', 1);
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = 0;    
if ( !empty($_GET['id'])) 
{
    $id = $_REQUEST['id'];
}           
if ( isset($_GET['id'])) 
{
    $stmt = $pdo->prepare("SELECT `path` FROM cats where `id` = :id"); 
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    if ($result = $stmt->fetch()) 
    {
        unlink("" . $result[0]);
        if($stmt = $pdo->prepare("DELETE FROM cats WHERE id = :id"))
        $stmt->bindParam(":id", $id, PDO::PARAM_INT);
        $stmt->execute();
    }     
    Database::disconnect();
 }      
?>

<form role="form" action="" method="post">
<input type="hidden" name="id" value="<?php echo $id;?>"/>
  <p class="alert alert-error">Are you sure?
    <div class="form-actions">
       <button type="submit" name="submit" class="btn btn-danger">Confirm</button>
       <a class="btn btn-info" href="main.php">Cancel</a>                      
    </div>
  </p>
</form>

点击delete.php按钮cats.php

后,此文件delete已打开

2 个答案:

答案 0 :(得分:4)

if (isset($_POST['submit']) && isset($_POST['id'])) 
{
    //then delete
}

答案 1 :(得分:2)

只需用下面的代码替换您的代码即可完成

<?php        
error_reporting(E_ALL); 
ini_set('display_errors', 1);

if (isset($_POST['submit']) && isset($_POST['id']))//YOU NEED TO CHECK IF THE FORM HAS SUBMITTED 
{
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $id = 0;    
    if ( !empty($_GET['id'])) 
    {
        $id = $_REQUEST['id'];
    }           
    if ( isset($_GET['id'])) 
    {
        $stmt = $pdo->prepare("SELECT `path` FROM cats where `id` = :id"); 
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->execute();
        if ($result = $stmt->fetch()) 
        {
            unlink("" . $result[0]);
            if($stmt = $pdo->prepare("DELETE FROM cats WHERE id = :id"))
            $stmt->bindParam(":id", $id, PDO::PARAM_INT);
            $stmt->execute();
        }     
        Database::disconnect();
     }
}          
?>

检查表单提交然后执行删除,否则当文件加载时,代码将被执行而无需任何验证。

如果有帮助,请不要忘记接受答案:)