My database is not updating - php

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);
}

Related

Check if value is exist in database jQuery and php

I m having a bit of trouble while validating value in database.
This is my html and js Code:
<input type="text" name="Unieke-voucher" value="" size="40" maxlength="8" minlength="8" id="voucher" aria-required="true" aria-invalid="false" placeholder="XYZ 1234">
var searchTimeout; //Timer to wait a little before fetching the data
jQuery("#voucher").keyup(function() {
vCode = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(vCode);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
var searchTimeout; //Timer to wait a little before fetching the data
jQuery("#voucher").keyup(function() {
vCode = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(vCode);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
function getUsers(vCode) {
jQuery.ajax({
url: 'voucher.php',
type: 'GET',
dataType: 'json',
data: {value: vCode},
success: function(data) {
if(data.status) {
jQuery("#codeError").html('');
console.log(data);
} else {
jQuery("#codeError").html('Value not found');
}
console.log(data);
}
});
}
With this getting value with keyup event and sending to php script till here working fine.
And this is php script:
$dbname = "voucher";
$dbuser = "root";
$dbpass = "root";
$dbhost = "localhost";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$voucherCode = $_GET['VoucherCode'];
$voucherCode['status'] = false;
//echo $voucherCode;
$result = mysqli_query($conn, "SELECT * FROM VoucherCode WHERE `code` LIKE '$voucherCode' LIMIT 1");
if(mysqli_num_rows($result)) {
$userData = mysqli_fetch_assoc($result);
$voucherCode['code'] = $Code;
$voucherCode['status'] = true;
}
echo json_encode($voucherCode);
I am always getting status value even providing correct value.
When i print_r table like
$resultAll = mysqli_query($conn, "SELECT * FROM VoucherCode");
$data2 = mysqli_fetch_all($resultAll);
print_r($data2);
I am able to see all data is there.
I am not sure what i am doing wrong here. Can anyone help me with this please.
Thanks in advance.

PHP parsererror ajax get returns array of strings

I am having a problem trying to get around a "parsererror" that is returned from my ajax request, despite a response in devtools which is an array of strings. I have a click event that makes an ajax request to pull in information from a database. The result in dev tools is:
1["1","admin","admin#admin.com","test","2017-01-11 00:00:00"]
I was expecting it to be a json object { }.
The code I wrote for the click event is:
$('#viewProfile').on('click', function() {
$.ajax({
type: 'GET',
url: 'api.php',
data: "",
cache: false,
dataType: 'json',
success: function(data) {
var id = data[0];
var name = data[1];
$('#userDetails').html("<p>ID: " + id + " Name: " + name + "</p>");
},
error: function(request, error) {
$('#userDetails').html("<p>There was a problem: " + error + "</p>");
}
});
});
The php I wrote for api.php
session_start();
echo $_SESSION['user_session'];
//DECLARE VARS FOR DB
$db_host = "localhost";
$db_name = "dbregistration";
$db_user = "root";
$db_pass = "";
$db_tablename = "tbl_users";
//CONNECT TO DB
include 'dbconfig.php';
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
$dbs = mysqli_select_db($db_con, $db_name);
//QUERY DB FOR DATA
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
$array = mysqli_fetch_row($result);
//RETURN RESULT
echo json_encode($array);
I have tried in api.php to use json_encode($array, JSON_FORCE_OBJECT) along with changing the datatype to HTML, which obviously did not work. In short, my goal was to be able to fire the click event, send an ajax request to retrieve information from the database, based on the user id then return that to the #userDetails id on the page. I am stuck trying to get around the array of strings that seems to be the roadblock for me.
Remove this line:
echo $_SESSION['user_session'];
and change this:
$array = mysqli_fetch_row($result);
to this:
$array = mysqli_fetch_assoc($result);
EDIT: you should also be checking for success/failure of your various db-related statements:
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name) or die("there was a problem connecting to the db");
$dbs = mysqli_select_db($db_con, $db_name) or die("Could not select db");
and also
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
if (!$result) {
die("query failed");
}
This needs to be removed echo $_SESSION['user_session'] it is getting returned to ajax call and because it is on json the return is incorrect.

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.

setup webos list selector choices with ajax json response dynamically

I'm trying to develop an application which gets the the response from the MySQL database using ajax post and update in list selector, but the list is displaying empty, can some one help me out from this please.....
code for .js:
SecondAssistant.prototype.setup = function() {
this.selectorChanged = this.selectorChanged.bindEventListener(this);
Mojo.Event.listen(this.controller.get('firstselector'), Mojo.Event.propertyChange, this.selectorChanged);
this.names = [];
try {
new Ajax.Request('http://localhost/projects/testingasdf.php', {
method: 'post',
parameters: {
'recs': getallrecords,
'q': q
},
evalJSON: 'true',
onSuccess: function(response){
var json = response.responseJSON;
var count = json.count - 1;
for(i=0; i<count; i++){
this.names.push({
label: json[i].name,
value: '0'
});
}
this.controller.modelChanged(this.model);
}.bind(this),
onFailure: function(){
Mojo.Controller.errorDialog('Failed to get ajax response');
}
});
}
catch (e){
Mojo.Controller.errorDialog(e);
}
this.controller.setupWidget("firstselector",
this.attributes = {
label: $L('Name'),
modelProperty: 'currentName'
},
this.model = {
choices: this.names
}
);
};
code for php:
<?php
header('Content-type: application/json'); // this is the magic that sets responseJSON
$conn = mysql_connect('localhost', 'root', '')// creating a connection
mysql_select_db("test", $conn) or die('could not select the database');//selecting database from connected database connection
switch($_POST['recs'])
{
case'getallRecords':{
$q = $_POST['q'];
//performing sql operations
$query = sprintf("SELECT * FROM user WHERE name= $q");
$result = mysql_query($query) or die('Query failed:' .mysql_error());
$all_recs = array();
while ($line = mysql_fetch_array($result,MYSQL_ASSOC)) {
$all_recs[] = $line;
}
break;
}
}
echo json_encode($all_recs);
// Free resultset
mysql_free_result($result);
// closing connection
mysql_close($conn);
?>
I would move the model updating code out of the SecondAssistant.prototype.setup method and have it fire somewhere in SecondAssistant.prototoype.activate.
Also call modelChanged
this.controller.modelChanged(this.model);
There is a typo on bindEventListener - should be bindAsEventListener and the return of the bind should be a different object:
this.selectorChangedBind = this.selectorChanged.bindAsEventListener(this);

PHP file not successfully receiving AJAX variable

Here is what I have going on in my AJAX:
$('#submit-button').click(function(){
var twit = $('input#twittername').val();
var email = $('input#email').val();
if((email == "" || email == "you#address.com") && (twit == "" || twit == "#twittername")){
$('p#empty-error').fadeIn();
return false;
}
var datastring = 'email=' + email + '&twit=' + twit;
if(email != "you#address.com"){
$.ajax({
type: 'POST',
url: '/path/to/script1.php',
data: datastring,
success: function(){
$('#signup').fadeOut('slow',function(){
$('#email-response').fadeIn('slow');
});
}
});
return false;
}
if(twit != "#twittername"){
$.ajax({
type: 'POST',
url: '/path/to/script2.php',
data: datastring,
success: function(){
$('#signup').fadeOut('slow', function(){
$('#email-response').fadeIn('slow');
});
}
});
}
return false;
});
AJAX is returning the success function. And I can navigate directly to /path/to/script2.php, and it will add an empty record to my database. But for some reason, the PHP is not actually receiving and inserting the AJAX variable.
This was working before, and I'm unsure at what point it stopped. It's just a bit strange that it is two scripts that were both working, and now neither are.
Script one was written by me, and it inserts a blank record if I navigate straight to it:
<?php
$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pw';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$dbname = 'databasename';
mysql_select_db($dbname, $con);
$sql = "INSERT IGNORE INTO databasename (column) VALUES ('$_POST['twit']')";
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
echo 'record added successfully';
mysql_close($con);
Script two is modified from MailChimp, and this does nothing if I navigate straight to it, which is expected:
function storeAddress(){
// Validation
if(!$_POST['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_POST['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('66a7f17d87e96e439f7a2837e2963180-us1');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "b1ebe7c0ba";
if($api->listSubscribe($list_id, $_POST['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_POST['email']){ echo storeAddress(); }
?>
Any ideas where I'm going wrong?
Also: I can successfully alert the datastring, if that's any help.
Not sure if it is just a typo here, but this line won't work:
$sql = "INSERT IGNORE INTO databasename (column) VALUES ('$_POST['twit']')";
It should be (look at the quotes at the POST variale):
$sql = "INSERT IGNORE INTO databasename (column) VALUES ('".$_POST['twit']."')";
Besides that, you should never put a POST Variable directly into the SQL statement due to security reasons (have a look at SQL injections).
Needed to delete the top "return false." A fun way to spend 4 hours.

Categories