MySql. After HTML button is clicked - TRUNCATE database table - php

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 could you help me, please?
Here I'm trying to creeate button:
<input type="button" id='delete' class='delete' value='Truncate' onClick="$truncate">
</input>
I know this is wrong way to use PHP variable in HTML, but I don't know how to do It correctly.
Here is my PHP variable:
$truncate= "TRUNCATE TABLE myTable";
With connection to database is all right:
$mysqli = new mysqli("localhost","database","password","asd");
So maybe here is better method to create button for truncate database's table? Thank you.
UPDATED:
This won't work too, nothing happens after button is clicked.
if(isset($_POST['delete'])){
$delete= "TRUNCATE TABLE myTable";
}
?>
<input type="button" id='delete' class='delete' name="delete" value='Truncate' onClick="delete">
</input>

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>

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();
?>

Related

How to execute stored procedure on click Html button?

I need to execute stored procedure which is on database, to on click Html button!!
name of stored procedure: DeleteRow
<form action="">
<input type="button" value="Check" onclick="">
</form>
How I can execute using php?? Is it possible?
** SQL query:**
CALL `DeleteRow`();
You can try something like this:
HTML:
<input type='button' value='Call Procedure' id='BtnId'>
jQuery:
$(document).ready(function(){
$("#BtnId").on( 'click', function(){
$.ajax({
type : "POST",
url : "callsp.php",
success : function(text){
alert(text);
}
});
return false;
});
});
PHP: (callsp.php)
<?php
// connect to database
$connection = mysqli_connect("hostname", "username", "password", "db", "port");
// run the query
$result = mysqli_query($connection, "CALL DeleteRow") or die("Query Failed: " . mysqli_error());
// loop the result set
while( $row = mysqli_fetch_array($result) ) {
print_r( $row );
}
?>
Let's say you have stored procedure something like
DELIMITER $$
CREATE PROCEDURE getDetails()
BEGIN
SELECT * FROM tablename;
END$$
Now you can execute this in the following way in PHP
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// execute the stored procedure
$sql = 'CALL getDetails()';
// call the stored procedure
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error occurred:" . $e->getMessage());
}
while ($r = $q->fetch()){
/*
* Do something
*/
}
On click, you can implement Ajax to make it work. You can follow PHP Ajax Example

jQuery AJAX post to php probleme

when echo the variable on php it works , but for insert it to database it doesn't , what is the probleme I didn't see any issue on the code , thanks for help
HTML/JQUERY
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
<script>
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var age = $('#age').val();
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
</script>
php
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
error on console
POST http://localhost/validate.php 500 (Internal Server Error)
send # jquery-3.1.1.min.js:4
ajax # jquery-3.1.1.min.js:4
(anonymous) # jquery.PHP:26
dispatch # jquery-3.1.1.min.js:3
q.handle # jquery-3.1.1.min.js:3
mysqldb.php this is the php file to connect to the database
<?php
$conn = mysqli_connect('localhost', 'root', 'password' , 'database');
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
The query is "well" built.
The variables there are well encapsulated.
There's some security issues that you can fix by preventing against cross site scripting (XSS) and SQL injection. This is done at the query level.
There's lots of threads in Stack explaining how to do that.
Try and use mysqli in the following way:
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "your query here";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo $result ;
} `
Thank you for telling me to write the suggestion in an answer.
Thank you also for accepting as the right answer, that showed a lot of consideration from your side.
Try this to see the exact error:
<?php
try
{
$conn = new PDO("dbtype:host=yourhost;dbname=yourdbname;charset=utf8","username","password");
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
}
catch(PDOException $e ){
echo "Error: ".$e;
}
.....//

withdraw my information from sql using ajax&js, dont know what's worng

I am working on a chrome extension (freshment) and have a little problem.
I have a button, and I want that when button is clicked, to show my information from my database on my extension page.
HTML :
<button class="button" id="show" style="vertical-align:middle" onclick="myAjax()"><span>Show my purchaes</span></button>
<div id="showhere">
//this is where i want to show the info
</div>
Java Script :
$(document).ready(function(){
function myAjax() {
$.ajax({
url:"http://127.0.0.1/show.php",
data:{ action:'showhere' },
method:"POST",
success:function(data) {
('#showhere').html(data);
}
});
}
});
PHP :
<?php
if($_POST['action'] == 'showhere') {
$servername = "localhost";
$username = "root";
$password = "********";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ProductName, Amount, Date, WebStore FROM budget";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["ProductName"]."</td><td>".$row["Amount"]."</td><td>".$row["Date"]."</td><td>".$row["WebStore"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
}
?>
What I want it to do is pretty simple : I have a button and below I have a div called : "showhere", and in this div I want to take mysql info and write it.
your write i didnt write the exact problem, the problem is that the button doesnt do anything.
agian , thx!
I suggest you set it this way:
$(document).ready(function() {
$('#show').on('click', function(e) {
e.preventDefault();
$.ajax({
url: "http://127.0.0.1/show.php",
data: {
action: 'showhere'
},
method: "POST",
success: function(data) {
('#showhere').html(data);
}
});
});
});

Why do I obtain always error with ajax into my php web page?

I want delete a record from database and to do it I want use ajax..
So I have a table where I put into last td this:
<input type='image' src='./img/delete.png' onClick='deleteUser(".$utentiIscritti[$i][0].");' />
this is my deleteUser function:
function deleteUser(id){
$.ajax({
type:"post",
url: "deleteUserAjax.php",
data: {'id':id},
success: function(data){
console.log("OK");
location.reload();
},
error: function(xhr, status, error){
alert(xhr+"\n\n"+status+"\n\n"+error);
console.log("KO");
}
});
}
And this is my php page to connect to db and delelte the record:
<?php
$USERDB = "u";
$PASSWORDDB = "p";
$NAMEDB = "d";
$queryDeleteUser = 'delete from user where id = "'.$_POST['id'].'"';
$conn = mysql_connect("localhost", $USERDB, $PASSWORDDB)
or die("Errore nella connessione al database: " . mysql_error());
mysql_select_db($NAMEDB) or die("Errore nella selezione del database: " . mysql_error());
mysql_query($queryDeleteUser) or die("Errore nella query: " . $queryDeleteUser . "\n" . mysql_error());
dbDisconnect($conn);
But I obtain always (from every ajax request) error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
iscritti.php:80
Why???
You can consider two solutions.
Your code is buggy. Try to execute it on it's own. Just call it in your browser and check the result!
You have specified a relational path for your script. url: "deleteUserAjax.php", try instead an absolute path and check the result (url: "http://yourdomain.com/deleteUserAjax.php")
Maybe make it more cleaner:
HTML part:
<input type='image' src='./img/delete.png' value='<?=$id?>'>
jQuery part:
$(document).ready(function(){
$("#delete").on("click", function(){
var data = $(this).val();
$.ajax({
method: "POST",
url: "page_you_handle_it.php?action=delete",
data: {'id':id}
}).done(function(data){
//here you get response of your delete function!
});
});
});
PHP part:
$host = "[HOST]"; //Like localhost
$user = "[USER]"; //Like root
$pass = "[PASS]"; //Like 123
$db = "[DB]"; //Like users
$con = mysqli_connect($host, $user, $pass, $db) or die ("Conntecting the Database gone wrong");
$id = $_POST['id'];
$query_str = "DELETE FROM user WHERE id = '$id'";
$query = mysqli_query($con, $query_str);
if (!$query) //Do not run the `$query` in the return parts because it already runs when you say `if (!$query)`
{
echo 'Delete gone wrong';
}
else
{
echo 'Delete succes!';
}

Error Code 0 in edit form jquery grid

i am a newbie with php and im trying to use jquery grid, with the form edit, and delete.
I am implementing the edit , it is appearing - error Status: 'error'. Error code: 0 ,when i press the submit button ,the error apears but the changes are made...
my grid...
<script>
var lastsel;
$(function() {
$("#toolbar").jqGrid({
mtype: 'POST',
editurl: 'http://www.onetag.pt/eulen/edit.php',
caption:"Tags",
colNames:['TagID','Nome', 'Descricao', 'Tipo'],
colModel:[
{name:'tagID',index:'tagID',hidden:true},
{name:'name',index:'name',editable:true},
{name:'description',index:'description',editable:true},
{name:'type',index:'type'}
],
datatype:"json",
height:421,
rownumWidth:40,
pager:'#ptoolbar',
rowList:[10,20,30],
rowNum:10,
sortname:'tagID',
sortorder:'desc',
url:'/tags/list/',
viewrecords:true,
width:740
});
$("#toolbar").jqGrid('navGrid','#ptoolbar',{del:true,add:false,edit:true,search:true});
$("#toolbar").jqGrid('filterToolbar',{stringResult:true,searchOnEnter:false});
});
</script>
and the editurl.php
<?php
// connect to the database
$dbhost = "localhost";
$dbuser = "blah";
$dbpassword = "blah";
$database = "blah";
$tablename = "tags";
$db = mysql_connect($dbhost, $dbuser, $dbpassword)
or die("Connection Error: " . mysql_error());
mysql_select_db($database) or die("Error conecting to db.");
//mysql_set_charset('utf8',$database);
mysql_query("SET NAMES 'utf8'");
if($_POST['oper']=='add')
{
}
if($_POST['oper']=='edit')
{
$id = mysql_real_escape_string($_POST['id']);
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$sql = "UPDATE ".$tablename." SET name ='".$name."', description ='".$description."' WHERE tagID = ".$id;
$result=mysql_query($sql) or die(mysql_error());
mysql_close($db);
}
if($_POST['oper']=='del')
{
}
?>
i select the first row, and press edit button
then it appears the edit form...
then ive put the desired changes...
then press the submit button and the error appears...
i close the edit form, and press f5 to refresh, and the datafields have changed...

Categories