Mysql
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Mysql

PDO xóa hàng được chỉ định khỏi bảng

Trên thực tế, không ai ở đây thực sự có thể trả lời điều này chỉ với mã bạn hiển thị ở đây. Nhưng cả @ultranaut và @devJunk đều đóng đinh nó khá nhiều. Khi tôi viết hàm ban đầu cho bạn, biểu mẫu của bạn cho phép người dùng thêm bản ghi vào cơ sở dữ liệu và có nút để "Xóa tất cả lịch sử công việc" nhưng không có phương pháp xóa bản ghi riêng lẻ.

Tôi đã viết hàm để:

  • chuyển giá trị chuỗi 'all' dưới dạng $rowId tham số sẽ xóa tất cả các bản ghi (đó là ứng dụng cần thiết)
  • chuyển một id hàng cơ sở dữ liệu dưới dạng $rowId tham số sẽ chỉ xóa hàng cụ thể đó (không cần thiết vào thời điểm đó nhưng có thể thêm nó vào)

Bởi vì bạn chỉ có một nút duy nhất tại thời điểm để xóa mọi thứ, tôi chỉ thực hiện điều đó với kiểm tra này:

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

Nếu bạn muốn xóa một bản ghi cụ thể, bạn cần thực hiện hai việc:

Thêm một nút hoặc nút tương tự trên trang đầu tiên của bạn để xóa một bản ghi riêng lẻ.

<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> 

Thêm kiểm tra ở trang thứ hai để xem liệu nút này có được nhấn hay không và gọi hàm chuyển trong id được cung cấp.

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 được sửa đổi lần cuối:

// 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> 



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Thay đổi datadir trên tệp my.ini không được tôn trọng trong WAMP

  2. Java MySQL executeUpdate () trả về điều gì cho CHÈN TRÊN CẬP NHẬT KHÓA DUPLICATE?

  3. Chèn nhiều giá trị vào nhiều cột từ một mảng dữ liệu bằng cách sử dụng câu lệnh PDO được chuẩn bị cho MySQL

  4. Không thể tìm ra cách chạy mysqli_multi_query và sử dụng kết quả từ truy vấn cuối cùng

  5. Làm cách nào để cài đặt máy khách MySQL dòng lệnh trên mac?