update table in database with ajax - php

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

Related

How to subtract from mysql database after pressing html button?

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.

My database is not updating

So,
I am a beginning 'nerd' and my job is now to make a kind of schedule where people can put their name in the input. I work with JS with the following code:
var timeoutId; $('form input').on('input propertychange change', function() {
console.log('Invoer bewerking');
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
saveToDB();
}, 1000); }); function saveToDB() { console.log('Opslaan naar Database');
form = $('.formulier24');
$.ajax({
url: "ajax.php",
type: "POST",
data: form.serialize(),
beforeSend: function(xhr) {
$('.HowAbout').html('Opslaan...');
},
success: function(data) { console.error(data) ;
var jqObj = jQuery(data);
var d = new Date();
$('.HowAbout').html('Opgeslagen om: ' + d.toLocaleTimeString());
},
}); } $('.formulier24').submit(function(e) {
saveToDB();
e.preventDefault(); });
and the AJAX file is as the following code:
<?php include ('connect.php'); if(isset($_POST['formulier24'])) {
$userName = $_POST['userName'];
$hours = $_POST['hours'];
$sql = "UPDATE evenement SET userName = '$userName' WHERE hours = '$hours'";
mysql_select_db('u7105d15197_main');
$retval = mysql_query($sql, $conn);
if (!$retval) {
die('Could not update data: ' . mysql_error());
}
echo " Updated data successfully\n";
mysql_close($conn); } ?>
The website says it is saving, but the updated information won't show up in the database. Does anybody know what I am doing wrong in this situation? P.S. it is a auto update form without a button.
I suspect your problem is that your UPDATE query is trying to update a row that doesn't exist. A REPLACE query will insert data, or replace it if there is a conflict with a table key.
While you're fixing that, you may as well toss out the code you have above. Give me 30 seconds with that web page and I could erase your whole database. (For example, what would happen if someone posted Hours as foo' OR 1=1 OR 'foo?)
It's a matter of personal preference, but I find PDO much easier to work with. It's less verbose and allows for much easier building of prepared statements, which are an essential security measure for any web application. It also allows you to use modern error handling methods like exceptions.
<?php
/* this block could be in a separate include file if it's going to be reused */
$db_host = "localhost";
$db_name = "u7105d15197_main";
$db_user = "user";
$db_pass = "asldkfjwlekj";
$db_opts = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
);
$conn = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass, $db_opts);
if(isset($_POST['formulier24'])) {
$sql = "REPLACE INTO evenement SET userName = ?, hours = ?";
$parameters = array($_POST["userName"], $_POST["hours"]);
try {
$stmt = $conn->prepare($sql);
$result = $stmt->execute($parameters);
$return = "Updated data successfully!";
} catch (PDOException $e) {
$return = "Could not update data! Error: " . $e->getMessage();
}
header("Content-Type: application/json");
echo json_encode($return);
}

PHP - How to get the selected item from dropdown menu populated from query before POST

I would like to know how do I get the selected name from a dropdown menu, being populated by a query using phpmyadmin, to display a picture according to the selection.
For example, if the users selects "Mountains" from the drop down menu I want to be able to use that value and make another query to get the specific image URL from the database and display it, and every time the user changes selection the image changes accordingly.
And yes, I know, mysql commands are deprecated.
If you need any more details let me know.
<select name='picker'>";
<?php
mysql_connect('localhost','root','');
mysql_select_db('...');
$sql = "...";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] ."</option>";
}
$selectoption = $_REQUEST['picker'];
mysql_connect('localhost','root','');
mysql_select_db('...');
$sql3 = "...";
$image = mysql_query($sql3);
?>
<img src="<?php echo $image; ?>">
Create 2 Files
main.php
fetchimage.php
Note: Both files should be on same location, if root folder they look like this
main.php
fetchimage.php
if inside folder assuming folder name is alpha then
alpha/main.php
alpha/fetchimage.php
Now create main.php file and put following PHP and jQuery code in it.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
mysql_connect('localhost','root','');
mysql_select_db('...');
?>
<select name="picker" id="picker">
<?php
$sql = "SELECT * FROM table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row['name'];?>"><?php echo $row['name'];?></option>
<?php } ?>
</select>
//Here Show the Images
<div id="imged"></div>
jQuery
//JQuery library always comes first.
<script>
$(document).ready(function() {
$("#picker").change(function(){
var name=$(this).val();
alert(name); //This will show an alert when value selected, remove this **alert** in production mode, use it only in development mode.
var dataString = 'name='+ name;
$.ajax({
type: "POST",
url: "fetchimage.php",
data: dataString,
cache: false,
success: function(data){
$("#imged").html(data);
}
});
});
});
</script>
More information about jQuery change function and Ajax Method
Bind #picker change function with <select>
Bind Ajax success function with id="imged" to display the image
Now create second file name fetchimage.php and put following code in it nothing else.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
mysql_connect('localhost','root',''); //Put Database Connection Here
mysql_select_db('...'); //Put Database Name Here
if(isset($_POST['name'])){
$selectoption = mysql_real_escape_string($_POST['name']);
$sql = "SELECT Image FROM table WHERE name = '$selectoption'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//This will show the image inside <div id="imged"></div>
echo '<img src="'. $row["Image"] .'" alt="" />';
}
?>
Side Note: keep in mind, mysql is deprecated, should start using mysqli now.
MySQLi (Procedural Example)
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
//Conntection Credentials
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Run Query
$sql = "SELECT imagename FROM table";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["imagename"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
OP requested an example code and provided other detail e.g (database) via email.
You can use ajax on select onchange event then change the content of the image.

Validate promo code from MySql table and mark as "used" when form is submitted

I have an HTML form starting with an input field, where the user have the option to write a promo code to get some discount ....
What I am trying to do here. I need to create a keyup functionto check if the typed code is found in the MySql Promo Codes table.
If found, write something in the placeholder ...., else, write something else ....
Also if the form is submitted in need the PHP to write 'Yes' in the code corresponding MySql Used column...
<form id="form" class="form" name="RevitForm" action="form_revit_architecture_submitted" method="post" enctype="application/x-www-form-urlencoded" accept-charset="UTF-8">
<div class="field" style="background-color:#f3f3f3;">
<span id="promo-msg" style="color:#093; position:relative; bottom:3px; font-style:italic; font-size:13px">[HTML is replaced when successful.]</span>
<center><input style="font-family:Lato; text-align:center; max-width:200px;" type="text" id="PromoCode" name="PromoCode" maxlength="5" size="15px" placeholder="Promo Code"></center>
</div>
//other input fields
</form>
<!-- Promotion Code Match -->
<script>
$("#PromoCode").keyup(function() {
if ($(this).val().length == 5) {
//post the code and check the it in the MySql table thru the PHP file "request.php"
//if code found {write something in $(#promo-msg) } else {do something else}
}
});
</script>
And in the PHP in need to excute something like
<?PHP
$code = ucwords($_POST['PromoCode']);
$con=mysqli_connect("localhost","x","y","academy_database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
// if $code is found and the corresponding `Used` column does not == 'Yes' return as found
//else return as not found
?>
To do that, we need 2 files.
HTML, form + jQuery AJAX keyup event and check DB
PHP connect to DB to check the promo code
1.HTML
<html>
<head>
<title>Promo check</title>
<!-- load jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//the min chars for promo-code
var min_chars = 10;
//result texts
var checking_html = 'Checking...';
//when keyup
$('#code').keyup(function(event){
//run the character number check
if($('#code').val().length == min_chars){
//show the checking_text and run the function to check
$('#Promo_code_status').html(checking_html);
check_code();
}
});
});
//function to check the promo code
function check_code(){
//get code
var code = $('#code').val();
//use ajax to run the check
$.post("check_code.php", { code: code },
function(result){
//if the result is 0
if(result == 0){
//show that the code is correct
$('#Promo_code_status').html(code + ' is correct.');
}else if(result == 1){
//show that the code is correct, but already has been used
$('#Promo_code_status').html(code + ' is already used correct.');
}else{
//show that the code is not correct
$('#Promo_code_status').html(code + ' is not correct.');
}
});
}
</script>
</head>
<body>
<input type='text' id='code'>
<div id='Promo_code_status'></div>
</body>
</html>
2.PHP: check_code.php
You will need to use your connection data ($host, $user, $pass, $dbdb) and maybe change the table & field names.
<?php
//connect to database
$user = "";
$pass = "";
$host = "";
$dbdb = "";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//get the code
mysqli_real_escape_string($connect, $_POST['code']);
//mysql query to select field code if it's equal to the code that we checked '
$result = mysqli_query($connect, 'select promoCode, used from testtable where promoCode = "'. $code .'"');
$record = mysqli_fetch_array($result);
//if number of rows fields is bigger them 0 that means the code in the database'
if(mysqli_num_rows($result) > 0){
if($record['used'] == 0) {
//and we send 0 to the ajax request
echo 0;
} else{
//and we send 1 to the ajax request
echo 1;
}
}else{
//else if it's not bigger then 0, then the code is not in the DB'
//and we send 2 to the ajax request
echo 2;
}
?>
db_code = mysqli_query($con," SELECT * FROM `Promo Codes` WHERE (`Code` LIKE '".$code."') AND (`Used` <> 'Yes') ");
Do it like this:
"SELECT * FROM Promo Codes WHERE Code LIKE '$code' AND Used='yes' "
Also,To update parameter 'used':
UPDATE Promo Codes SET used='Yes' WHERE Code= '$code'
For the keyup function, you need to learn about AJAX requests. Since it's the medium for communicating with the server through the client
jQuery AJAX: http://api.jquery.com/jquery.ajax/

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