I want to do a really simple task: check if an inserted id matches one found in a mysql database. If no match, an alert box will appear displaying an invalid id message. When I run the following, the server response is:
SELECT * from users where id = $idnotfound
Any clue what might be wrong? When a valid id is inserted, it will alert that the id is invalid, when it should do nothing.
<html>
<head>
<script type = "text/javascript">
var xhr;
if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
function callServer()
{
// Create the id number
var id = document.getElementById("id").value;
// Build the URL to connect to
var url = "/dataExtract.php?id=" +escape(id);
// Open a connection to the server
xhr.open("GET", url, true);
// Setup a function for the server to run when it is done
xhr.onreadystatechange = idExists;
// Send the request
xhr.send(null);
}
function idExists()
{
if ((xhr.readyState == 4) && (xhr.status == 200))
{
var response = xhr.responseText;
if (response != 'found'){
alert ("Invalid ID");
return;
}
}
}
</script>
</head>
<body>
<form method = "POST" action = "<?php echo $_SERVER['PHP_SELF']; ?>">
<p>ID:<input type = "id" id="id" name="id" size="20" maxlength="40" onBlur = "callServer();"/></p>
<input type="submit" id="submit" name ="submit" value="Submit" /><br><br>
</form>
</body>
</html>
PHP SCRIPT:
<?php
//connect to server....
$id = $_GET["id"];
$query = 'SELECT * from users where id = $id';
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if (empty($result))
{
$response = "notfound";
echo $response;
}
else
{
$response = "found";
echo $response;
}
// Close connection to the database
mysql_close($con);
?>
Your issue is that you’re using
$idin a single quoted string, where it won’t be evaluated. It’s being interpreted literally.You need to use double quotes for your query string. Or you could use string concatenation instead.
OR