My AJAX Application always returns “found”

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. The problem that I have is my script ALWAYS returns found, even if the id does not exist in the database. Here is my script, any idea what is wrong?

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

Answers


Try:

$query = 'SELECT * from users where id = '.(int) $id;
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$num_rows = mysql_num_rows($result);
if($num_rows > 0) {
echo "found";
}
else {
 echo "not found";
}

You're using single quotes instead of double quotes on your query assignment. You must use double quotes or string concatenating.

$query = "SELECT * from users where id = $id";

OR

$query = 'SELECT * from users where id = ' . $id;

And you're also probably doing this in the insert, which is why it's always being 'found'.


Need Your Help

How to add extra data to wx.TreeCtrl items? wxpython

python user-interface wxpython

How can I add extra data to the appended tree items in the wx.TreeCtrl named fileTree below. I read data from a text file into an array to build the tree. The append items in the tree are the filen...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.