sql >> Database teknologi >  >> RDS >> Mysql

PDO slet specificeret række fra tabellen

Faktisk ville ingen her rigtig være i stand til at svare på dette med bare den kode du viser her. Men @ultranaut og @devJunk klarede begge stort set det. Da jeg oprindeligt skrev funktionen for dig, tillod din formular en bruger at tilføje poster til databasen og havde en knap til "Ryd al arbejdshistorik", men havde ikke en metode til at slette individuelle poster.

Jeg skrev funktionen således at:

  • passer strengværdien 'all' som $rowId parameter ville slette alle poster (hvilket er, hvad applikationen har brug for)
  • passer et databaserække-id som $rowId parameter ville slette netop den specifikke række (ikke nødvendigt på det tidspunkt, men det gav mening at tilføje det)

Fordi du kun havde den ene knap på det tidspunkt til at slette alt, implementerede jeg kun det med denne kontrol:

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

Hvis du vil slette en bestemt post, skal du gøre to ting:

Tilføj en knap eller lignende på din første side, der sletter en individuel post.

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

Tilføj et flueben på den anden side for at se, om denne knap blev trykket, og ring til funktionen, der passerer i det medfølgende 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']);    
}   

Endelig ændret 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> 



  1. Lumen - Opret databaseforbindelse ved kørsel

  2. MySql upsert og auto-increment forårsager huller

  3. Få første/sidste n poster pr. gruppe af

  4. MySQL CONVERT_TZ()