我有 MySQL 5.1,我希望用基于 IP 的最近城市填充一个选择框。我已经下载了 Max Mind 的 GeoLite 数据库,但我不知道如何只填充靠近 IP 的城市。我还想根据IP“预选”最近的城市。
我写了一些代码,但我只能显示我找到的国家的所有城市。那么,有人可以告诉我如何做到这一点吗?
<?php
$ip=$_SERVER["REMOTE_ADDR"];
$user="user";
$pass="password";
$conn=mysql_connect("localhost:3306",$user,$pass);
$link=mysql_select_db("db");
$ipConv=ip2long($ip);
$sql="SELECT CITY,REGION,LATITUDE,LONGITUDE
FROM location, blocks
WHERE $ipConv
BETWEEN blocks.startIpNum
AND blocks.endIpNum
AND location.locId = blocks.locid";
$result=mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($result))
{
$tcity=$row['CITY'];
$tregion=$row['REGION'];
}
$sql2="SELECT COUNTRY FROM location WHERE CITY='$tcity'";
$result2=mysql_query($sql2);
while($row2 = mysql_fetch_assoc($result2))
{
$country=$row2['COUNTRY'];
}
$sql3="SELECT CITY,REGION FROM location WHERE COUNTRY='$country' GROUP BY REGION";
$result3=mysql_query($sql3);
?>
<form>
<select>
<?php
while ($row3=mysql_fetch_assoc($result3))
{
?>
<option <?php if ($row3['CITY']==$tcity){ ?> selected="selected"<?php } ?>)>
<?php echo $row3['CITY']; ?>
</option><?php
} ?>
</select>
</form>
谢谢