PHaeLiX
PHaeLiX

Reputation: 85

Error passing variable from AJAX to PHP for MySQL query

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.

Upvotes: 0

Views: 799

Answers (1)

Nick Coons
Nick Coons

Reputation: 3692

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.

Upvotes: 1

Related Questions