Php PDO从表中删除指定行

Php PDO从表中删除指定行,php,mysql,pdo,delete-row,Php,Mysql,Pdo,Delete Row,我有一个小问题。。。 我正在使用PDO,我的部分代码是从数据库中的表中删除特定的行。 我的代码如下 function deleteFromWorkWhere($db,$table,$user,$rowId){ switch($table){ case 'work': $tbl = 'work'; break; } if($rowId=='all'){ // de

我有一个小问题。。。 我正在使用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']);  
    }

实际上,这里没有人能够用你在这里展示的代码来回答这个问题。但是@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');    
}
如果要删除特定记录,需要做两件事:

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

最后修订的php:
//删除记录的函数
//$table是要从中删除的表
//$user是当前用户名
//$rowId是要删除的记录的行id
//如果$rowId作为字符串“all”传递,
//将删除所有匹配的记录
函数deleteFromWhere($db、$table、$user、$rowId){
//PDO将自动清理大多数VAR
//但是,PDO中的参数不能替换表名和列名。
//在这种情况下,我们只需要手动过滤和清理数据。
//通过不保留默认大小写或使用返回错误消息的默认大小写,您可以确保只使用希望使用的值。
// http://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-name-as-parameter
交换机($表){
“工作”案例:
$tbl='work';//如果要开始从其他表中删除,请在此处添加更多内容
打破
}
如果($rowId=='all'){//删除所有记录
$sql='DELETE FROM'.$tbl.'WHERE username=?';/“?”s此处将替换为下面的数组元素
$stmt=$db->prepare($sql);
$stmt->execute(array($user));//这些数组元素将以相同的顺序替换上面的“?”
//检查错误
如果($stmt->errorCode()==0){
//无错误,显示警报和刷新页面
返回“警报(“所有工作历史记录已成功清除!”);window.location=“addCV.php”;
}否则{
//有错误
$errors=$stmt->errorInfo();
返回'alert('Error deleting work history!:'.$errors[2].');window.location=“addCV.php”;';
}
}
elseif($rowId){//删除指定的行
$sql='DELETE FROM'.$tbl.'WHERE username=?AND id=?';/“?”s此处将替换为下面的数组元素
$stmt=$db->prepare($sql);
$stmt->execute(array($user,$rowId));//这些数组元素将以相同的顺序替换上面的“?”
$impacted_rows=$stmt->rowCount();//获取受此更改影响的行数
返回$infected_行。“行已删除”;
//检查错误
如果($stmt->errorCode()==0){
//无错误,显示警报和刷新页面
返回“警报(“所选工作历史记录已成功清除!”);window.location=“addCV.php”;
}否则{
//有错误
$errors=$stmt->errorInfo();
返回“警报”(“删除工作历史记录时出错:”.$errors[2]”);window.location=“addCV.php”;
}
}
else{///返回错误
}
}   
如果(isset($_POST['clear_work'])){
//有关`deleteFromWhere(),请参见上述函数声明中的参数说明`
deleteFromWhere($db,'work',$_SESSION['username','all');
}
//添加下面的复选框
如果(isset($_POST['clear_this_work'])){
//有关'deleteFromWhere(),请参见上面函数声明中参数的说明`
deleteFromWhere($db,'work',$\u SESSION['username',$\u POST['clear\u this\u work']);
}   
HTML:


不起作用有多特别?@ultranaut它不会删除特定的行,它什么也不会做如果你没有收到任何错误,听起来像是
$user
和/或
$rowId
没有设置为你期望的值。@ultranaut奇怪的是,当我想全部删除它们时,它会起作用,这意味着,
$user
没有任何问题。如果您在代码中看到的所有If-isset都是这样的
If(isset($\u POST['clear\u education']){deleteFromEduWhere($db,'education',$\u SESSION['username'],'all');}
但是对于会话后的特定行,我们没有什么东西,我不知道该写什么我认为您上面发布的代码缺少实际的函数声明,但是如果您在调用函数时没有
$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> 
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']);    
}   
// 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']);    
}   
<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>