Error passing variable from AJAX to PHP for MySQL query - php

I am getting an error when trying to pass a variable from AJAX to PHP for a MySQL query. I have tried hardcoding to make sure that the query works and it does, but when I try to dynamically pass the variable it is telling me the following "Error: Unknown column '$searchid' in 'where clause'". I am trying to send the value of a dropdown box to ajax to pull back data from a MySQL database. The returned data will then be put into 2 text boxes to be edited. Note: I am trying not to use the jQuery framework for this so I can get a better understanding of what the AJAX is actually doing.
AJAX code
function ajax_post(){
var request = new XMLHttpRequest();
var id = document.getElementById("editorginfo").value;
request.open("POST", "parse.php", true);
request.setRequestHeader("Content-Type", "x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
document.getElementById("orgeditname").value = return_data;
document.getElementById("orgeditphone").value = return_data;
}
}
request.send("id="+id);
}
PHP Parse code
<?php
include_once('../php_includes/db_connect.php');
$searchid = $_POST['id'];
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
$user_query = mysqli_query($db_connect, $sql) or die("Error: ".mysqli_error($db_connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$orgid = $row["id"];
$orgname = $row["orgname"];
$orgphone = $row["orgphone"];
echo $orgname, $orgphone;
}
?>
It's been a while since I have had time to work with code so I believe everything I used is still relevant. Also I know I havent put any sanitizing in yet, I wanted to make sure I can get the function working first, and I am the only one with access currently.
Thanks in advance for any help.

To solve your immediate issue, you'll want to change this:
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
Into this:
$sql = "SELECT * FROM orginfo WHERE id = $searchid";
Since your string is in single quotes, it is literally passing the string '$searchid' into the query rather than the value of $searchid.

Related

Jquery - parsererror - Unexpected end of JSON input

I'm trying to retrieve info from my database and display the information in a table generated by JQuery. I had done this before, and with using the exact same code it doesn't work anymore. I've looked up several other questions about this, but none of them has given me an answer.
This is the situation: An user select a value from the select menu, by selecting a value, that value gets sent and used to retrieve the right key for the right data. Then, by pressing a button the data should appear in a table. In order to accomplish this, I am using 3 ajax calls, one for populating the select box, one to send the right value, and another one to retrieve the needed data. The first two work perfectly, but not the last one.
My browser receives the data (see below) but the table does not appear and I'm getting a 'Unexpected end of JSON input' error. Can anyone help me out with this?
HTML/Jquery of the Ajax with the error:
function BekijkGegevens() {
$.ajax({
type: 'GET'
, data: {}
, dataType: 'json'
, url: "https://projectmi3.000webhostapp.com/webservices/bekijk.php"
, success: function (rows) {
$('#output').append("<table><tr><th> datum</th><th>stand</th></tr>")
for (var i in rows) {
var row = rows[i];
var datum = row[1];
var stand = row[0];
$('#output').append("<tr><td>" + datum + "</td><td>" + stand + "</td></tr>");
}
$('#output').append("</table>");
}
, error: function (JQXHR, TextStatus, ErrorThrow) {
console.log(JQXHR);
console.log(TextStatus);
console.log(ErrorThrow);
}
})
}
PHP:
<?php
include_once('confi.php');
error_reporting(E_ALL);
if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);
$sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";
$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);
$data2=array();
while ($row = mysqli_fetch_row($result))
{
$data2[]=$row;
}
echo "{data:" .json_encode($data2). "}" ;
}
?>
Thanks for any help that you can provide.
EDIT: Forgot to put my browser network, here it is.
http://puu.sh/uzI4f/a9ed1e0be5.png
EDIT2: I've split the PHP script into two seperate files, and tries to use a session variable to pass the needed key as suggested in the comments. Yet I am still getting the same error. Hereby the two new PHP files:
This one is used to send the key from Jquery to PHP:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);
$_SESSION['teller'] = $teller;
}
?>
This one is used to get the needed information:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_SESSION['teller']))
{
$sql2='SELECT sta_stand,sta_datum FROM stand WHERE teller_id ="' .$_SESSION['teller'].'"' ;
$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);
$data2=array();
while ($row = $result-> fetch_row())
{
$data2[]=$row;
}
echo json_encode($data2);
}
?>
First, some warnings (in accordance with this link):
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Don't believe it?
You should test against the session variable in your second script, which should look like this:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_SESSION['teller']))
{
$teller = $_SESSION['teller'];
$sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";
$result = $conn -> query($sql2);
$data2=array();
while ($row = mysqli_fetch_row($result))
{
$data2[]=$row;
}
echo json_encode(['data'=> $data2]);
}
?>
Please note that I am also appending the 'data' properly to the JSON instead of just trying to "glue" (as said by Denis Matafonov) the JSON string together.
Dont try to glue data to string, like this:
echo "{data:" .json_encode($data2). "}" ;
Use simple
echo json_encode(['data'=> $data2]);
It should produce the same result if everything goes right, but wouldnt break up json if your $data2 is null
Declare your $data2 in the begginng, before if statement:
$data2 = [];
if (isset($_POST['teller'])) {
//do stuff and redefine $data2 or fill it;
}
//always echo valid json, event if no $POST["teller"] has arrived
echo json_encode(['data' => $data2]);

How to Update MYSQL table in PHP using JSON

I am working with jstree. The tree works fine.I send JSON to a PHP file with JQuery. This works fine.
$("#button3").click(function(){
//json object
var objtree = $("#container").jstree(true).get_json('#', { 'flat' : true });
var fulltree = JSON.stringify(objtree);
var myarray = $.parseJSON(fulltree);
var params = { myarray: myarray };
var paramJSON = JSON.stringify(params);
//sending to php file
$.post('update.php',{ data: paramJSON });
});
Then in the php file (update.php), I update mySQL table by: deleting all the records in $tablename ($sql1) and inserting the information gotten from the JSON ($sql2). This works fine.
<?php
$connection = mysqli_connect($servername, $user,$password,$database) or die("Error " . mysqli_error($connection));
$test = $_POST["data"];
$obj = json_decode($test, true);
$data = $obj["myarray"];
//first query
$sql1 = "DELETE FROM $tablename";
$connection ->query($sql2);
foreach($data as $val){
//second query
$sql2 = "INSERT INTO $tablename(id,parent,text) VALUES('".$val['id']."', '".$val['parent']."', '".$val['text']."')";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
}
mysqli_close($connection);
?>
But what I want is not to delete everything in the table then insert them brand new. But an SQL statement to update the old values (using the id maybe?) and insert the new values.
So like:
If id exists:
update row
else:
insert new row
I am new to PHP and SQL. So my problem is knowing the PHP syntax for accessing JSON array information. So please any example would be much appreciated!
First, you'll use a PHP function to get all rows matching the given ID. if this returns one, you'll use another function to UPDATEwhere the ID == valueFromPreviousFunction, else you'll call a function to INSERT a new row.
$check = mysqli_query($connection,"SELECT * FROM `your_table_name` WHERE `id`='".$val["id"]."'");
if(mysqli_num_rows($check)==1)
{
//Update the row
$update = mysqli_query($connection,"UPDATE `table_name` SET `parent`='".$val["parent"]."', `text`='".$val["text"]."' WHERE `id`='".$val["id"]."'");
}
else
{
//Insert the row
}
There isn't a command to do what you want in a single operation.
You should either fetch all ids beforehand and run an update for each one of them separately, or use REPLACE INTO.
Be careful with REPLACE INTO, though: if a row matching a primary/unique key exists, it first deletes it and then inserts a new one rather than updating the existing row.

handling a error in mysql using php caused by ajax

I am submitting a form using ajax,
function ajax_post() {
// ...(code);
var hr = new XMLHttpRequest();
var url = "http://domain.com/submit_action.php";
var vars = "element_1=" + ln + "&element_2=" + fn;
hr.open("POST", url, true);
hr.send(vars);
// ...(code);
}
having the php exc the query:
$sql = 'SELECT *
FROM ' . table. '
WHERE ' . $db -> sql_build_array('SELECT', $data);
$result = $db -> sql_query($sql);
$sql = 'INSERT INTO ' . table. ' ' . $db -> sql_build_array('INSERT', $data);
$db -> sql_query($sql);
In my above code, it will run. But when the 'fn' and 'ln' are the same or already exist in the db, then there will be a error. But because im using ajax to submit it, I stay on the current page of the form without getting a error, without knowing if the query exc or not.
Question is, is there a way to have php tell ajax what kind of error occured during the exc of query? Thanks in advance.
anything echoed during your php script will be returned into the hr.responseXML and hr.responseText attributes.
Catch these 2 values within your hr.onreadystatechange callback, whenever the status is OK, to know what happened in your php.
hr.onreadystatechange = function() {
if (hr.readyState == 4 && (hr.status == 200)) {
//do something with hr.responseText
}
}
I personnaly systematically encapsulate my php answers inside a generic xml response, with a customized status: error/ok/business error, and a customized message, so I know what to do with it at the javascript layer.
In addition to this, I would suggest you catch the 1062 mysql error to know that the error is due to an already existing value, and raise a more user-friendly message.

Get JSON data FROM a PHP/MySQL query into a html tag using jquery

Hi guys I´m new at stackoverflow and also new at Jquery
Well hope I can make myself understandable. Here is what I want: I have made a query to my MySQL db, using a class with PHP
public function User($id) {
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$arr[]=array(
'id'=>$values['idUsers'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
'lname2'=>$values['lname2'],
'email'=>$values['email'],
'phone'=>$values['phone'],
'address'=>$values['address'],
'bday'=>$values['bday'],
'password'=>$values['password']
);
}
echo '{"user":'.json_encode($arr).'}';
}
Then I have a php code where I call this function
$name = $user->User($id);
I think this works ok (if I´m wrong please help). Now what I´m really trying to do is getting the values from the JSON array into specific divs, example:
$.getJSON("user.php",function(data){
$.each(data.user, function(i,user){
name = user.name;
$(name).appendTo('#getname');
});
});
And inside my HML i Have a <p id="getname"></p>wich is the tag I want the value to be displayed
But no value is displayed, why?, what am I doing wrong?
Thanks for the help I apreciate it
Your JSON is malformed. You are appending a bunch of objects {.1.}{.2.}{.3.}. Instead, try {"users":[{.1.},{.2.},{.3.}]}.
In PHP you'll do something like this (note that I've changed the response type to JSON-P rather than JSON by adding a callback parameter):
public function User($id) {
$users = array();
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$users[] = array(
'id'=>$values['idUsers'],
'name'=>$values['name']
// etc.
);
}
$obj['users'] = $users;
$callback = (empty($_GET["callback"])) ? 'callback' : $_GET["callback"];
echo $callback . '(' . json_encode($obj) . ');';
}
Then you'll be able to do:
$.getJSON("user.php?callback=",function(data){
$.each(data.users, function(i,user){
$('#getname').append(user.name);
});
});
probably safer to do like this:
echo json_encode(array("user" => $arr));
on the other end you would receive an object which, I would suggest iterating like this:
var k;
for (k in data.user){
$("#getname").append($("<span></span>").html(data.user[k].name));
}
Given that you are fetching information for one user only, following I would suggest
$id = (int) $_GET["id"]; // or wherever you get it from.
if ($r = $db->mysql_fetch_assoc()){
$response = array(
"name" => $r["name"];
);
echo json_encode($response);
} else {
echo json_encode(array("error" => "Could not get name for user " . $id));
}
Then, on front-end, all you need to do is:
if (typeof(data.name) != "undefined"){
$("#getname").html(data.name);
} else if (typeof(data.error) != "undefined"){
$("#getname").html(data.error); //or handle otherwise
}
You've misinterpreted your JSON structure. You're appending your DB rows to an array, and embedding that inside an object. If you'd do a console.log(user) inside your .getJSON call, you'd see you'll have to do:
user[0].name
instead. As well, your code assumes that the user ID exists, and returns data regardless of how many, or how few, rows there actually are in the result set. At minimum your JS code code should check users.length to see if there ARE are any rows to begin with. Beyond that, unless you're doing it in another section of code somewhere, that $id value is probably coming from the web page, which means your query is vulnerable to SQL injection attacks.
OK got it,
was a php code error and JSON structre as marc said, here I´m gonna post what finally I had
PHP Class
public function User() {
$users = array();
$this->connect($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='1'");
$values = mysql_fetch_array($sql);
$users[] = array(
'id'=>$values['id'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
...//rest of values
);
echo json_encode($users);
}
PHP module to get class
include"class.php";
$user = new Users();
$user->User();
Now how did I got the values using JQuery
$.getJSON('user.php', function(data){
$('wherever_you_want_to_point_at').text(data[0].name);
});
Hope it helps someone,
Thanks again guys, very very helpful
Take care you all

Actionscript 3 MySQL query using PHP

Want to send in State, City, County variables from Flash to PHP page:
function retrieve() {
var scriptRequest:URLRequest = new URLRequest("http://localhost:8080/GSM/KJVold.php");
var scriptLoader:URLLoader = new URLLoader();
var scriptVars:URLVariables = new URLVariables();
scriptLoader.addEventListener(Event.COMPLETE, handleLoadSuccessful);
scriptLoader.addEventListener(IOErrorEvent.IO_ERROR, handleLoadError);
scriptVars.State = this.whichState;
scriptVars.City = this.whichCity;
scriptVars.County = this.whichCounty;
scriptRequest.method = URLRequestMethod.POST;
scriptRequest.data = scriptVars;
scriptLoader.load(scriptRequest);
function handleLoadSuccessful($evt:Event):void
{
MovieClip(parent).info_txt.text = scriptRequest;
}
My PHP page reads:
//connection to database stuff
$result = mysql_query("SELECT info FROM kjvold WHERE State='$State' AND City='$City' AND
County='$County'");
while($row = mysql_fetch_array($result))
{
print "info = " . $row['info'];
}
When I trace actionscipt variables I see named pairs going to page. When I hard code PHP page I can see the right output, but when trying to use variables to PHP in the text box I get object URLRequest not the County info I'm seeking. It sure would help if someone can help me with this. Thanks in advance, Annie.
I've never used ActionScript before but in your PHP script instead of
$County
$State
$City
I'm quite sure you need to use
$_POST["County"]
$_POST["State"]
$_POST["City"]
Also it might be an idea to escape your SQL query from injections or other invalid inputs by wrapping the variable in a mysql_real_escape_string() function
Ie:
$_POST["County"]
Becomes:
mysql_real_escape_string($_POST["County"])

Categories