MySQL的。单击HTML按钮后 - TRUNCATE数据库表

时间:2013-11-27 12:55:04

标签: php html mysql database button

所以我需要简单的东西,我需要在我的网站上创建按钮,点击按钮后,它应该截断数据库表,但我不能自己成功。那么,你能帮助我吗?

我在这里尝试按下按钮:

<input type="button" id='delete' class='delete' value='Truncate' onClick="$truncate">
</input>

我知道这是在HTML中使用PHP变量的错误方法,但我不知道如何正确地做到这一点。

这是我的PHP变量:

$truncate= "TRUNCATE TABLE myTable";

连接数据库是可以的:

$mysqli = new mysqli("localhost","database","password","asd");

所以也许这里有更好的方法来创建截断数据库表的按钮?谢谢。

更新:

这也行不通,单击按钮后没有任何反应。

    if(isset($_POST['delete'])){
    $delete= "TRUNCATE TABLE myTable";
    }
?>
<input type="button" id='delete' class='delete' name="delete" value='Truncate' onClick="delete">
</input>

2 个答案:

答案 0 :(得分:1)

在这里,试一试。

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 method="post" action="delete_table.php">
<input type="submit" id='delete' class='delete' name="delete" value='Truncate'></input>
</form>

答案 1 :(得分:0)

我到目前为止还没有jQuery专家,但也许是这样......当然没有经过考验

<强>的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();


?>