Reputation: 11
I have a HTML page with a text box in which a user would type a country into, and then AJAX and PHP would query a mysql database of countries and print them in a DIV below. The code works just fine apart from one thing. If I type 'A' in the text box, it only prints one result on screen, 'Afghanistan', whereas it should be printing every country starting with 'A'. I imagine the fault lies with the response text, but how would I print out multiple responses, or does that even make sense :P Below is the relevant code.
The PHP database query
<?php
$country=$_REQUEST['country']; //get the country sent by Ajax
$connection = mysql_connect("localhost","MYUSERNAME","MYPASSWORD");
mysql_select_db("countrydb", $connection);
$result=mysql_query("SELECT * FROM countries WHERE country LIKE '%$country%'",$connection);
if($row = mysql_fetch_array($result))
echo $row['country'];
else
echo "noresults";
mysql_close($connection);
?>
This is the relevant javascript
function showcountryStatus() {
if (request.readyState == 4) {
if (request.status == 200) {
if (request.responseText == "noresults") {
document.getElementById('results').innerHTML="No Results";
} else {
document.getElementById('results').innerHTML=request.responseText;
}
}
}
}
So basically my search is returning only the first result, whereas it should be returning a whole list. Thank you in advance!
Upvotes: 1
Views: 306
Reputation: 21763
As you can read on the page about mysql_fetch_array
you should use it in a loop, e.g.
while ($row = mysql_fetch_array($result)) {
echo $row['country'];
}
Now you're only fetching the first result.
Upvotes: 1