I have two buttons: one for create a table in my database and another to delete the table, but when I click on the button "Drop Table" the message shown is: "Error create table: Table 'post' already exists", because it enters the first if on php file. I can not find how to solve this.
Here go my code:
html
<button id="loadButton" type="button" class="btn btn-success" style="margin-top:5px;">Create Table</button>
<button id="deleteButton" type="button" class="btn btn-danger" style="margin-top:5px;">Drop Table</button>
dash.js file
$('#loadButton').click(function() {
$.ajax({
url: 'connectdb.php',
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus);
}
});
});
$('#deleteButton').click(function() {
$.ajax({
type: 'POST',
url: 'connectdb.php',
data: "drop",
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus);
}
});
});
connectdb.php file
// Create table
$sql="CREATE TABLE Post(
id_post int Primary Key,
titulo varchar(100) not null,
imagem longblob,
descricao varchar(1000) not null,
hashtag varchar(100) not null
)";
// Execute query
if(!isset($_POST["drop"])){
if (mysqli_query($con,$sql)) {
echo "Table created with success";
} else {
echo "Error create table: " . mysqli_error($con);
}
}
if (isset($_POST["drop"])) {
$sql1="DROP TABLE IF EXISTS Post;";
if (mysqli_query($con,$sql1)) {
echo "Table deleted";
} else {
echo "Error: " . mysqli_error($con);
}
}
What I'm doing wrong?
data: "drop",. Trydata: {drop:'drop'}. Although it is not a great idea to create/drop tables like this.connectdb.phpis password protected, or anyone will be able to delete your tables by accessing the url directly.