MySql. After HTML button is clicked - TRUNCATE database table

前端 未结 2 1056
闹比i
闹比i 2021-01-15 02:24

So I need simple thing, I need to create button in my website, after button is clicked, It should truncate database table, but I can\'t do It successfully by myself. So coul

相关标签:
2条回答
  • 2021-01-15 03:01

    Here, give this a try.

    PHP (delete_table.php)

    <?php
    // CONNECT TO THE DATABASE
    $DB_HOST = "your_host";
    $DB_NAME = "your_DB_name";
    $DB_USER = "username";
    $DB_PASS = "password";
    
    $dbc = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME)
    or die('Error connecting to MySQL server');
    
    if(isset($_POST['delete'])){
    $query = "TRUNCATE TABLE `yourTable` "; // replace yourTable with one to delete
    $result = mysqli_query($dbc,$query)
    or die('Error deleting table.');
    }
    else {
    echo "Sorry";
    }
    ?>
    

    HTML form

    <form method="post" action="delete_table.php">
    <input type="submit" id='delete' class='delete' name="delete" value='Truncate'></input>
    </form>
    
    0 讨论(0)
  • 2021-01-15 03:26

    I'm by far no jQuery expert but maybe something like this....untested of course

    jQuery

    $(document).ready(function() {
    
        $('#delete').click(function() {
    
            var table = $('#table').val(); //where #table could be an input with the name of the table you want to truncate
    
            $.ajax({
               type: "POST",
               url: "truncate.php",
               data: 'table='+ table,
               cache: false,
               success: function(response) {
                    alert('table dropped');
                },
                error: function(xhr, textStatus, errorThrown) {
                   alert('request failed');
                }
            });
    
        });
    });
    

    PHP (truncate.php)

        try {
            // create a new instance of a PDO connection
            $db = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $e) {
            // if the connection fails, display an error message
            echo 'ERROR: ' . $e->getMessage();
        }
    
        $table = $_POST['table'];
    
        $sql = 'TRUNCATE TABLE '.$mytable;
    
        $stmt = $db->prepare($sql);
        $stmt->execute();
    
    
    ?>
    
    0 讨论(0)
提交回复
热议问题