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
Related
I am trying to subtract 0.05 from the cash amount of a player in my database once they push a button. Here is what I got so far.
My database:
Database name: accounts
Table: users
The Column I want to affect: cash_amount
Html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'subtract5.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<button id="playbutton" onclick="myAjax();location.href='5game.html'">Play (-5ยข)</button>
Php file: (subtract5.php)
<?php
UPDATE `accounts`.`users` SET `cash_amount` = '`cash_amount` - 0.05'
Thanks for helping, I am kind of a noob :)
This the following code, however dont exactly copy paste it, read the comments there are a few variables you might have to change and get from the database.
<?php
$servername = "servarname";
$username = "username";
$password = "password";
$dbname = "dbName";
// Create connection
$userid = // You must enter the user's id here.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$newAmount = $previousAmount - 0.05;
$sql = "UPDATE users SET cash_amount = '$newAmount'";
$result = $conn->query($sql);
if($result)
{
echo "Query Executed Successfully!";
}
else
{
echo mysqli_error($conn);
}
$conn->close();
?>
Try executing that request. That's nothing more than a string without quotes around it. I'm sure that PHP considers it as an error.
You should consider learning PHP and MySQL before attempting to code a project.
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;
}
.....//
I have two file, test.html & test.php. I would like to display the result of an SQL query via jQuery AJAX.
test.php outputs proper JSON, but I'm not able fetch the same on clicking upon the button "Fetch Data". Is it wrong way of using AJAX?
Once fetching the data in test.html, how do I access the contents?
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$ajax({
url:'test.php',
type:'get',
dataType:'json',
success:function(data){
alert(data);
console.log(data['success']);
console.log(data.success);
}
});
});
});
</script>
</head>
<body>
<button>Fetch Data</button>
</body>
</html>
test.php
<?php
$dbuser="root";
$dbname="test";
$dbpass="root";
$dbserver="localhost";
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT ID, UserName, Status FROM user_details1";
// Execute query
$result = mysql_query($sql_query) or die(mysql_error());
$jsonArray = array();
while ($row = mysql_fetch_array($result)){
$jsonArrayItem = array();
$jsonArrayItem["ID"] = $row["ID"];
$jsonArrayItem["UserName"] = $row["UserName"];
$jsonArrayItem["Status"] = $row["Status"];
array_push($jsonArray, $jsonArrayItem);
//echo '<option value='. $row['id'] . '>'. $row['login'] . '</option>';
}
mysql_close($con);
$tableData = array(
"data" => $jsonArray
);
header('Content-Type: application/json');
echo json_encode($tableData,JSON_UNESCAPED_SLASHES);
die();
?>
How do I display/access/print the fetched result contents (AJAX section)?
Make a function like this
var dataToSend = "My Data";
$(button).on("click",function(event){
$.ajax({
method: "POST",
url: "test.php",
data: { pDataToSend: dataToSend }
}).done(function( data ) {
$('.results').empty();
$('.results').append(data);
});
});
And make a div like this
<div class="results></div>
In your PHP file you can read the POST using this code.
$foo = $_POST['pDataToSend'];
Also, your test.php file is all over the place. Use a PDO like this
//connect and setup database example
try {
$db = new PDO("mysql:host=localhost;dbname=second;port=8889","root","root");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo 'Could not connect to the database.105';
exit();
}
//select,insert,delete, update from database example
try{
$results = $db->prepare("SELECT * FROM articles WHERE article_id = ? AND user_id = ?");
$results->bindParam(1,$var);
$results->bindParam(2,$var2);
$results->execute();
$hold = $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit();
}
Here i want to call the php function with some parameter that will be held in some jquery function.
I have php function that takes one parameter and executes the sql query.
and also i have a jquery function where i am getting different values when select item from dropdown box.
now i want to pass the value of dropdown box to php function, how can i do this?
here is what i have done
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
// here i want to pass this variable value to php function
});
php
function productManagement($procat){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT product_name,product_category,product_image_url FROM product_list where product_category='$procat'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["product_name"]."</td><td><a href=''><span class='glyphicon glyphicon-remove'></span>Remove</a></td><td><a href='edit-product.php'><span class='glyphicon glyphicon-edit'></span>Edit</a></td></tr>";
}
} else {
echo "No results found";
}
$conn->close();
}
How can i do this?
Another way is to use Ajax like :
Jquery code:
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
// here i want to pass this variable value to php function
-----------------------------------------------------
$.ajax({
url: 'newFunctionFile.php',
type: 'POST',
data: 'category='+category,
success: function(data) {
//you can add the code to show success message
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
});
and you have to create a file for php function let say file name is newFunctionFile.php as i have mention in ajax call:
if(isset($_POST['category'])) {
productManagement($_POST['category']);
}
function productManagement($procat){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT product_name,product_category,product_image_url FROM product_list where product_category='$procat'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["product_name"]."</td><td><a href=''><span class='glyphicon glyphicon-remove'></span>Remove</a></td><td><a href='edit-product.php'><span class='glyphicon glyphicon-edit'></span>Edit</a></td></tr>";
}
} else {
echo "No results found";
}
$conn->close();
}
How about something along these lines.
In your javascript:
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
location.href = location.href + "?val="+category; //reload the page with a parameter
});
And then in your PHP, add this code as your function call
if(isset($_GET['val'])) { //if 'val' parameter is set (i.e. is in the url)
productManagement($_GET['val']); //call function, with that parameter
}
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();
?>