/    Sign up×
Community /Pin to ProfileBookmark

Pulling data from mySql table using PHP and AJAX

Hi, I am a PHP newbie and need some help with this storelocator I am building.

I would like to user to select the county they would like to find store located in by using a drop down menu.

this is the html and AJAX for the user interface

[code=html]<html>
<head>
<script type=”text/javascript”>
function showUser(str)
{
if (str==””)
{
document.getElementById(“txtHint”).innerHTML=””;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(“txtHint”).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”getuser.php?q=”+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name=”shop” onchange=”showUser(this.value)”>
<option value=””>Select a County/Region:</option>
<option value=”1″>West Midlands</option>
<option value=”2″>East Midlands</option>
<option value=”3″>South West</option>
<option value=”4″>South East</option>
<option value=”5″>The North</option>
<option value=”6″>Scotland</option>
<option value=”7″>Wales</option>
<option value=”8″>London</option>
<option value=”9″>Herefordshire</option>
</select>
</form>
<br />
<div id=”txtHint”><b>Try one of these outlets or shops</b></div>

</body>
</html> [/code]

I have a table called store in mySQL db with the following fields: company_name, address, county, country, phone, web_site.

I would like the user to be able to select e.g. “Herefordshire” and all shops with county = Herefordshire should be displayed. This is the page for the php operation:

[code=php]<?php
$q=$_GET[“q”];

$con = mysql_connect(‘localhost’, ‘shops’, ‘pwds123’);
if (!$con)
{
die(‘Could not connect: ‘ . mysql_error());
}

mysql_select_db(“shops”, $con);

$sql=”SELECT * FROM shop WHERE county = ‘”.$q.”‘”;

$result = mysql_query($sql);

echo “<table border=’1’>
<tr>
<th>Company Name</th>
<th>Address</th>
<th>City/Town</th>
<th>County</th>
<th>Post Code</th>
<th>Phone</th>
<th>Web Site</th>
</tr>”;

while($row = mysql_fetch_array($result))
{
echo “<tr>”;
echo “<td>” . $row[‘company_name’] . “</td>”;
echo “<td>” . $row[‘address’] . “</td>”;
echo “<td>” . $row[‘city_town’] . “</td>”;
echo “<td>” . $row[‘county’] . “</td>”;
echo “<td>” . $row[‘post_code’] . “</td>”;
echo “<td>” . $row[‘phone’] . “</td>”;
echo “<td>” . $row[‘web_site’] . “</td>”;
echo “</tr>”;
}
echo “</table>”;

mysql_close($con);
?> [/code]

The above doesn’t pull any data – which I assume it because I don’t know how to set up the query properly.
The reason I am using AJAX on the html script is because I found an example on the web but I realise it might not be the best way but am not capable to determine that.

Appreciate any help or nudge in the right direction. As I said, am a newbie so need some detailed help.

to post a comment
PHP

12 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJun 11.2011 — Your AJAX function in the JavaScript is calling a page called "getuser.php". Is that the correct file? (I'm asking because the PHP file doesn't seem to have anything to do with getting a user. ? )
Copy linkTweet thisAlerts:
@olaandauthorJun 13.2011 — hi nogdog - yes getuser.php is the correct file....
Copy linkTweet thisAlerts:
@maurycyJun 13.2011 — could you try this?
[CODE]$sql="SELECT * FROM shop WHERE county = {$q}"; [/CODE]
Copy linkTweet thisAlerts:
@olaandauthorJun 13.2011 — thanks for taking the time to reply - I tried your suggestion but no luck. I don't get any error messages or warnings either.... Perhaps using java is a bit too convoluted?
Copy linkTweet thisAlerts:
@maurycyJun 13.2011 — did you tried to get all records from that call?
[CODE]$sql="SELECT * FROM shop";[/CODE]
does it return anything?

change that code too to check if everything is ok:
[CODE]if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}[B][COLOR="Red"]else{
alert('something is wrong');
}[/COLOR][/B][/CODE]


try to start your PHP file directly: getuser.php?q=[your value] and see if there is any result
Copy linkTweet thisAlerts:
@olaandauthorJun 13.2011 — good idea - Yes [code=php]$sql="SELECT * FROM shop";[/code] returns everything so should be nearly there......
Copy linkTweet thisAlerts:
@maurycyJun 13.2011 — did you tried other suggestions?
Copy linkTweet thisAlerts:
@olaandauthorJun 13.2011 — ...hmm did just now..and when I change the script to [code=html]<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
} else{
alert('something is wrong');
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>[/code]


it goes back to not pulling any data at all....
Copy linkTweet thisAlerts:
@olaandauthorJun 14.2011 — With some great tips from above author I managed to narrow it down and by

changing:
[code=html]<option value="8">London</option>
<option value="9">Herefordshire</option>[/code]


to:
[code=html]<option value="london">London</option>
<option value="herefordshire">Herefordshire</option>[/code]


it is now working fine.

Installing Firebug helped be see what the query I was using was trying to do.
Copy linkTweet thisAlerts:
@maurycyJun 14.2011 — hehe, so you was sending wrong value ?

have a nice day ?

Cheers
Copy linkTweet thisAlerts:
@olaandauthorMay 10.2012 — right, I would now like to modify this script so that the html dropdown menu automatically pulls any county that has been added to the database (at the moment I have to add the counties manually to the dropdown). Here is the code for the html page
[code=php]<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>

</head>
<body>

<form>
<select name="shop" class="output" onChange="showUser(this.value)">
<option value="">Select a County/Country:</option>
<option value="bristol">Bristol</option>
<option value="edinburgh">Edinburgh</option>
<option value="inverness">Inverness</option>
<option value="largs">Largs</option>
<option value="somerset">Somerset</option>
<option value="suffolk">Suffolk</option>
<option value="Tyne and Wear">Tyne and Wear</option>
<option value="west sussex">West Sussex</option>
<option value="international">**International**</option>
</select>
</form>
<br />
<div id="txtHint"><b></b></div>

</body>
</html> [/code]


and here is the code from the referenced getuser file:

[code=php]php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'dbname', 'dbpwd');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("dbname", $con);

$sql="SELECT * FROM shop WHERE county = '".$q."'";

$result = mysql_query($sql);

echo "<table width='775' border='0'>
<tr>
<th align=left>Name</font></th>
<th align=left>Address</th>
<th align=left>Town</th>
<th align=left>Country</th>
<th align=left>Post Code</th>
<th align=left>Phone</th>
<th align=left>Web Site</th>
</tr>";

while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['company_name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['city_town'] . "</td>";
echo "<td>" . $row['region'] . "</td>";
echo "<td width='80'>" . $row['post_code'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "<td>" . $row['web_site'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysql_close($con);
?> [/code]



Many Thanks in advance for any answer
Copy linkTweet thisAlerts:
@maurycyMay 10.2012 — Basicly what you want to do is populate SELECT box with data existing in database and you can do that in many ways, I'll mention two main solution:

SELECT content is generated on server side in country.php

[code=php]
$mysql = mysql_query("SELECT Country FROM country_table ORDER BY Country DESC");
$html = ''
while($row = mysql_fetch_assoc($mysql)){
$html .= '<option value="'.$row['Country'].'">'.$row['Country'].'</option>';
}
echo $html;
[/code]


that will generate list like this one:

<option value="bristol">Bristol</option>

<option value="edinburgh">Edinburgh</option>

<option value="inverness">Inverness</option>

<option value="largs">Largs</option>

<option value="somerset">Somerset</option>

<option value="suffolk">Suffolk</option>

<option value="Tyne and Wear">Tyne and Wear</option>

<option value="west sussex">West Sussex</option>

then all you need to do is add that to your desired SELECT box

other solution is to export JSON object with Country/County names and then manipulate it from JS level, but i didn't saw any JS framework in your code so i suppose first solution will fit you.


BTW:
[code=php]$sql="SELECT * FROM shop WHERE county = '".$q."'";[/code]
bad bad bad bad bad, never EVER trust users, they are all filthy beasts waiting for mysql injection
×

Success!

Help @olaand spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...