PDO从表

时间:2015-04-30 15:44:05

标签: php mysql pdo delete-row

我有点问题...... 我正在使用PDO,我的部分代码是从数据库中的表中删除特定行。 我的代码如下......

function deleteFromWorkWhere($db,$table,$user,$rowId){
        switch($table){
            case 'work':
                $tbl = 'work';
                break;
        }
        if($rowId=='all'){ // delete all records
            $sql = 'DELETE FROM '.$tbl.' WHERE username=?';  // "?"s here will get replaced with the array elements below
            $stmt = $db->prepare($sql);
            $stmt->execute(array($user)); // these array elements will replace the above "?"s in this same order
            // check for errors 
            if($stmt->errorCode() == 0) {
                // no errors, show alert and refresh page
                return '<script type="text/javascript">alert("All work history was successfully cleared!"); window.location="CV.php"; </script>';
            } else {
                // had errors
                $errors = $stmt->errorInfo();
                return '<script type="text/javascript">alert("Error deleting work history!: '.$errors[2].'"); window.location="CV.php"; </script>'; 
            }
        }
        elseif($rowId){ // delete specified row 
            $sql = 'DELETE FROM '.$tbl.' WHERE username = ? AND id = ?';  // "?"s here will get replaced with the array elements below
            $stmt = $db->prepare($sql);
            $stmt->execute(array($user,$rowId)); // these array elements will replace the above "?"s in this same order
            $affected_rows = $stmt->rowCount(); // get the number of rows affected by this change
            return $affected_rows.' row deleted.';
            // check for errors 
            if($stmt->errorCode() == 0) {
                // no errors, show alert and refresh page
                return '<script type="text/javascript">alert("Selected work history was successfully cleared!"); window.location="CV.php"; </script>';
            } else {
                // had errors
                $errors = $stmt->errorInfo();
                return '<script type="text/javascript">alert("Error deleting work history: '.$errors[2].'"); window.location="CV.php"; </script>';  
            }
        }
        else{ /// return error
        }
    }   
    if(isset($_POST['clear_work'])){
            deleteFromWorkWhere($db,'work',$_SESSION['username'],'all');    
    }
    if(isset($_POST['clear_selected_work'])){
            deleteFromWorkWhere($db,'work',$_SESSION['username']);  
    }

第一个if语句用于删除表中的所有数据以及我要使用的else以删除特定行,但它不起作用,是什么我做错了吗?

这是按钮......

<input type="submit" value="Clear Selected Work History" name="clear_selected_work" />

1 个答案:

答案 0 :(得分:2)

实际上这里没有人真的能够用你在这里展示的代码来回答这个问题。但@ultranaut和@devJunk几乎都钉了它。当我最初为您编写该函数时,您的表单允许用户将记录添加到数据库并具有“清除所有工作历史记录”的按钮,但没有删除单个记录的方法。

我写了这个函数,以便:

  • 传递字符串值'all'作为$rowId参数将删除所有记录(这是应用程序所需的)
  • 传递数据库行ID作为$rowId参数将仅删除该特定行(当时不需要但有意义添加它)

因为你当时只有一个按钮来删除所有内容,所以我只用这个检查实现了这个:

if(isset($_POST['clear_work'])){
        // see explanation of params in function declaration above for `deleteFromWhere()`
        deleteFromWhere($db,'work',$_SESSION['username'],'all');    
}

如果要删除特定记录,则需要做两件事:

在您的第一页上添加一个按钮或类似按钮,删除单个记录。

<form action="addCV.php" method="post"> 
    <input type="hidden" value="12345" name="clear_this_work" /><!--you'll need to set the value here to the database row id of the currently displayed record -->                  
    <input type="submit" value="Clear This Work Record" style="border: 1px solid #006; color:#F87F25; font: bold 16px Tahoma; border-radius:7px; padding:4px; background:#ffffff;"/>
</form> 

在第二页中添加一个检查以查看是否按下了此按钮并调用传递了提供的ID的函数。

if(isset($_POST['clear_this_work'])){
        // see explanination of params in function declaration above for `deleteFromWhere()`
        deleteFromWhere($db,'work',$_SESSION['username'],$_POST['clear_this_work']);    
}   

最终修改了php:

// a function that deletes records 
// $table is the table to delete from
// $user is the current username
// $rowId is the row id of the record to be deleted
// if $rowId is passed as the string "all", 
// all matching records will be deleted 
function deleteFromWhere($db,$table,$user,$rowId){
    // PDO will sanitize most vars automatically
    // however Table and Column names cannot be replaced by parameters in PDO. 
    // In this case we will simply want to filter and sanitize the data manually.
    // By leaving no default case or using a default case that returns an error message you ensure that only values that you want used get used.
    // http://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-name-as-parameter
    switch($table){
        case 'work':
            $tbl = 'work'; // add more here when you want to start deleting from other tables
            break;
    }
    if($rowId=='all'){ // delete all records
        $sql = 'DELETE FROM '.$tbl.' WHERE username=?';  // "?"s here will get replaced with the array elements below
        $stmt = $db->prepare($sql);
        $stmt->execute(array($user)); // these array elements will replace the above "?"s in this same order
        // check for errors 
        if($stmt->errorCode() == 0) {
            // no errors, show alert and refresh page
            return '<script type="text/javascript">alert("All work history was successfully cleared!"); window.location="addCV.php"; </script>';
        } else {
            // had errors
            $errors = $stmt->errorInfo();
            return '<script type="text/javascript">alert("Error deleting work history!: '.$errors[2].'"); window.location="addCV.php"; </script>';  
        }
    }
    elseif($rowId){ // delete specified row 
        $sql = 'DELETE FROM '.$tbl.' WHERE username = ? AND id = ?';  // "?"s here will get replaced with the array elements below
        $stmt = $db->prepare($sql);
        $stmt->execute(array($user,$rowId)); // these array elements will replace the above "?"s in this same order
        $affected_rows = $stmt->rowCount(); // get the number of rows affected by this change
        return $affected_rows.' row deleted.';
        // check for errors 
        if($stmt->errorCode() == 0) {
            // no errors, show alert and refresh page
            return '<script type="text/javascript">alert("Selected work history was successfully cleared!"); window.location="addCV.php"; </script>';
        } else {
            // had errors
            $errors = $stmt->errorInfo();
            return '<script type="text/javascript">alert("Error deleting work history: '.$errors[2].'"); window.location="addCV.php"; </script>';   
        }
    }
    else{ /// return error
    }
}   


if(isset($_POST['clear_work'])){
        // see explanation of params in function declaration above for `deleteFromWhere()`
        deleteFromWhere($db,'work',$_SESSION['username'],'all');    
}

// add the below check 
if(isset($_POST['clear_this_work'])){
        // see explanination of params in function declaration above for `deleteFromWhere()`
        deleteFromWhere($db,'work',$_SESSION['username'],$_POST['clear_this_work']);    
}   

HTML:

<form action="addCV.php" method="post">                         
    <input type="submit" value="Clear All Work History" name="clear_work" style="border: 1px solid #006; color:#F87F25; font: bold 16px Tahoma; border-radius:7px; padding:4px; background:#ffffff;"/>
</form> 
<!--  add the below -->
<form action="addCV.php" method="post"> 
    <input type="hidden" value="12345" name="clear_this_work" /><!--you'll need to set the value here to the database row id of the currently displayed record -->                  
    <input type="submit" value="Clear This Work Record" style="border: 1px solid #006; color:#F87F25; font: bold 16px Tahoma; border-radius:7px; padding:4px; background:#ffffff;"/>
</form>