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'.