In this am only deleting the record but i want to have backup once i click delete button. Also if the record is not inserted in the backup table (backup failed means) it should not delete and gives error message. And execution time should not take more time- Using in PHP,MYSQL,XAMPP

<?php

// connect to the database
include('connect-db.php');

// confirm that the 'id' variable has been set
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
    // get the 'id' variable from the URL
    $id = $_GET['id'];

    // delete record from database
    if ($stmt = $mysqli->prepare("DELETE FROM players WHERE id = ? LIMIT 1"))
    {
        $stmt->bind_param("i",$id);
        $stmt->execute();
        $stmt->close();
    }
    else
    {
        echo "ERROR: could not prepare SQL statement.";
    }
    $mysqli->close();

    // redirect user after delete is successful
    header("Location: view.php");
}
else
{
    // if the 'id' variable isn't set, redirect the user
    header("Location: view.php");
}

?>

1 Answers

1
Madhur Sharma On

make a replica of players table as players_backup and insert the data first to backup table and once you get the num rows after inserting is greater than zero that means the data has been inserted. after this you can delete the data from the players tables. Simple.

i am assuming that players and players_bkp have same schemas.

if (isset($_GET['id']) && is_numeric($_GET['id']))
{
    // get the 'id' variable from the URL
    $id = $_GET['id'];
    $sql  = "insert into players_bkp select * FROM players WHERE id = ? LIMIT 1";
    $stmt = $mysqli->prepare($sql);
    $rc = $stmt->bind_param('i',$id);
    $rc = $stmt->execute();
    $tid = $stmt->insert_id;
    $stmt->close();
    if($tid  > 0){  //that means record is inserted and you can actually delete the record from your players table
        // delete record from database
        if ($stmt = $mysqli->prepare("DELETE FROM players WHERE id = ? LIMIT 1"))
        {
            $stmt->bind_param("i",$id);
            $stmt->execute();
            $stmt->close();
        }
        else
        {
            echo "ERROR: could not prepare SQL statement.";
        }
        $mysqli->close();

        // redirect user after delete is successful
        header("Location: view.php");
    }
}
else
// if the 'id' variable isn't set, redirect the user
{
    header("Location: view.php");
}