How to subtract from mysql database after pressing html button? - php

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.

Related

ajax returns [object object]

i am making a quiz webapp with php and ajax where on click of radio button it triggers a function to get the new row in a database using ajax and php however it outputs object object inside the specified div element whenever the ajax success is called.
here is the ajax side of the code:
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var answer = $(this).val();
var question_id = $('#dataContainer').data('value');
$.ajax({
url:"quizengine.php",
method:"POST",
data:{
answer:answer,
question_id:question_id
},
dataType: 'json',
success:function(response){
console.info(response);
$('#question').text(response);
$('#answer_one').text(response);
$('#answer_two').text(response);
$('#answer_three').text(response);
}
});
});
});
</script>
and here is the php side of the code
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rubiqube";
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
?>
<?php
if (isset($_POST['answer'])) {
global $connection;
$answer = $_POST['answer'];
$question_id = $_POST['question_id'];
$result = mysqli_query($connection, "SELECT is_right FROM answers WHERE question_id='$question_id'");
$row = mysqli_fetch_assoc($result);
if (isset($row)) {
$correct = $row['is_right'];
if ($answer === $correct) {
$next = mysqli_query($connection, "SELECT Questions.question_id,Questions.lesson,Questions.instruction,Questions.question,Questions.image,Questions.option_type,Questions.question_value,Answers.answer_one,Answers.answer_two,Answers.answer_three,Answers.is_right FROM Questions LEFT JOIN Answers ON Questions.question_id = Answers.question_id WHERE Questions.question_id>'$question_id' ORDER BY Questions.question_id ASC LIMIT 1");
$nextrow = mysqli_fetch_assoc($next);
echo json_encode($nextrow);
exit();
}else{
echo "error";
exit();
}
}
}
?>
here is an image of what i am talking about
enter image description here
When the response comes back in the success callback, dataType: 'json' will convert it from json to an object (thus why you're seeing [object object]). You can't use the .text() method on it directly as that requires it to be a string. You may be able to do $('#question').text(response.key) depending on the data structure.
You need to simply either loop through the object and use the data, or access the properties directly (i.e. console.log(response.key)).
Here is some documentation from MDN on what to do with an object. Working with objects
Create an object of the Question on the server'side, then in your ajax response do this:
success:function(response){
$('#question').text(response.propertyName);
//propertyNamerefers to the one you made on the serverside
}

update table in database with ajax

i want to insert selected texts in my page in table with clicking on button in my page but my problem is it doenst insert . select text is correct i tested it.
response that i receive is my selected texts
This is my index page and i passed my texts into variable text
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
var text = $("span:not([dir=rtl])").text();
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{'text':text},
success:(function (response) {
alert(response);
})
})
})
})
</script>
this is my process.php that connects to database and perform query but runs else statement
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sahifeDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = 'update sahife_tbl set english ='. $_POST['text'].' where id=1 ';
$result = $conn->query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
You need to put " in update statement as datatype is text for field
change your query to:
$sql = 'update sahife_tbl set english ="'. $_POST['text'].'" where id=1 ';
Also use Prepared statement to prevent from sql injection
You need to put quotes around your string value in the query otherwise your DB will try to parse the text as part of the syntax and fall over.
$sql = "update sahife_tbl set english ='". $_POST['text']."' where id=1 ";
But again as mentioned in my comment on your question, this is super insecure, you want to use parameterisation instead - https://stackoverflow.com/a/60496/635522

retrieve from database and send to another php file

I have 2 php files one that retrieve from database, other one take each value came from the database. the problem: data is being sent as whole not row by row. so I can not have each value seperatly. I am trying to find smart way to do so.
first file:
$host = 'localhost';
$user = 'root';
$pass = '';
$db_name="bbbb";
$conn = new mysqli($host, $user, $pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = array(); // create an array
while( $row = $result->fetch_assoc()) {
echo $row ['input']; //if my database have 2 rows one with value t1 and other with t2.
}
?>
second file:
<script src = "https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function(){
retrieveData();
});
function retrieveData(){
$.post('quick.php',{}, function(data){
window.alert(data);
});
}
</script>
the output i have is a single alert with (t1 t2)
my desire output to be 2 alerts window. first one with value t1 second with value t2.
try This:
use json to your server side,
while( $row = $result->fetch_assoc()) {
echo json_encode($row['input']);
}
and on your second file:
$.post('quick.php',{}, function(data){
window.alert(data);
},"json");

How can i pass the jquery value to php function

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
}

jQuery calls a PHP file to get data from mysql database?

Ok so I have found a number of tutorials online and have followed each of them step by step. My problem is that I know javascript/jQuery much better than I know PHP and I cannot figure out how to even debug what is going wrong in that section. Basically I have a bunch of buttons and a from and when a button is pressed it determines what the default values are in the form.
jQuery Side
$(document).ready(function(){
// CSPC and ADDUPDATE TOGGLE ARE DEFINED GLOBALLY
$('ul#parts').on('click', 'button', function(){
ADDUPDATETOGGLE = "ADD";
CSPC = $(this).attr("data-cspc");
var form = $('div.sidebar form'),
sr = 0;
form.find("#cspc").val(CSPC);
$.ajax({
type: "GET",
url: "getRate.php",
data: "pid=A5843",
dataType: "json",
success: function(data){
sr = data;
}
});
form.find("#strokeRate").val(sr);
showForm();
});
});
PHP side
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$tableName = "part parameters";
$con = mysql_connect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$pid=$_GET["pid"];
if (empty($pid)){
echo "1"; //default rate
}
else{
$db=mysql_pconnect("localhost");//connect to local database
mysql_select_db("movedb", $db);//select the database you want to use
if (!$db){
echo ("error connecting to database");
}
else{
//connection successful
$sql = "SELECT 'Processing Rate (ppm)' FROM 'part parameters' WHERE 'Part Number' LIKE '" . $pid . "'";//sql string command
$result=mysql_query($sql);//execute SQL string command
//result contains rows
$rows = mysql_fetch_row($result)
echo json_encode($rows["Processing Rate (ppm)"]);
}
}
?>
Any ideas why sr is not getting set?
Am I way off base?
I will also shamelessly note that I do not know what $user and $pass should be set to. I cannot find that explained anywhere
Thanks in advance!
EDIT: I followed most of the directions below and now when I run
http://localhost/getRate.php?pid=A5843
it says "No database selected." Also, I dont have access to our original MS Access file now (one of my team members has it) but once I get it I will make all the headers into one word headers. This is our first job with web programming/database management so we are constantly learning.
$user and $pass should be set to your MySql User's username and password.
I'd use something like this:
JS
success: function(data){
if(data.status === 1){
sr = data.rows;
}else{
// db query failed, use data.message to get error message
}
}
PHP:
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$tableName = "part parameters";
$con = mysql_pconnect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$pid = $_GET["pid"];
if(empty($pid)){
echo json_encode(array('status' => 0, 'message' => 'PID invalid.'));
} else{
if (!$dbs){
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));
}
else{
//connection successful
$sql = "SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //sql string command
$result = mysql_query($sql) or die(mysql_error());//execute SQL string command
if(mysql_num_rows($result) > 0){
$rows = mysql_fetch_row($result);
echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
}else{
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find processing rate for the give PID.'));
}
}
}
?>
As another user said, you should try renaming your database fields without spaces so part parameters => part_parameters, Part Number => part_number.
If you're still having trouble then (as long as it's not a production server) put this at the top of your php file:
error_reporting(E_ALL);
ini_set('display_errors', '1');
This will output any errors and should help you work out what's going wrong.
Your DB query code is incorrect:
$sql = "SELECT 'Processing Rate (ppm)' FROM 'part parameters' WHERE 'Part Number' LIKE '" . $pid . "'";//sql string command
using ' to quote things in the query turns them into STRINGS, not field/table names. So your query is syntactically and logically wrong. Your code is simply assuming success, and never catches the errors that mysql will be spitting out.
The query should be:
SELECT `Processing Rate (ppm)`
FROM `part parameters`
WHERE `Part Number` = '$pid'
Note the use of backticks (`) on the field/table names, and the use of single quotes (') on the $pid value.
Then you execute the query with:
$result = mysql_query($sql) or die(mysql_error());
If this fails, you will get the error message that mysql returns.
And in the grand scheme of things, your code is vulnerable to SQL injection attacks. Better read up and learn how to prevent that before you go any farther with this code.
sr it's outside the success callback function. Start putting it into the success function and see what happens
$.ajax({
type: "GET",
url: "getRate.php",
data: "pid=A5843",
dataType: "json",
success: function(data){
sr = data;
form.find("#strokeRate").val(sr);
}
});
remember that, if data is expected to be a json, it will become a js object, so you will not be able to use data directly
Here is a compilation of the above with up-to-date code.
jQuery
$(document).ready(function(){
...
$.ajax({
type: "GET",
url: "getRate.php", //see note "url"
data: {
pid : "A5843"
//, ... : "..."
},
dataType: "json",
success: function(data){
sr = data;
}
});
...
});
url > test your request-URL including any parameters (eg. http://localhost/XYZ/getRate.php?pid=251) and then enter it here, after removing anything after the '?' symbol (including '?')
data > https://api.jquery.com/Jquery.ajax/
PHP
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$pid=$_GET['pid']; //get the parameter from URL
$con = mysqli_connect($host, $user, $pass, $databaseName);
//$dbs = mysqli_select_db($con, $databaseName);
if (empty($pid)){
echo json_encode(array('status' => 0, 'message' => 'pid invalid.'));
}
else{
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
//if (!$dbs)
//echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));
else{//connection successful
$sql = SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //https://www.geeksforgeeks.org/how-to-prevent-sql-injection-in-php/
$result = mysqli_query($con, $sql) or die(mysql_error());//execute query
if($result){
$rows = mysqli_fetch_row($result);
echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
}
else
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find results'));
}
mysqli_free_result($result);
mysqli_close($con);
}
?>
Please note that I am no PHP-expert. Any comments welcome.

Categories