现在差不多可以用了。我可以在表格中得到结果,但由于某种原因,它们不太正确。
搜索坐标x 100 &y 100
我得到x 1-25 &只有Y 1-25而不是x 74-125 &74 - 125 y
<?php
$x = $_POST['x'];
$y = $_POST['y'];
mysql_connect ("localhost","user","pass") or die (mysql_error());
mysql_select_db ("db");
$res = mysql_query("select * FROM table WHERE (x between $x-25 AND $x+25) AND (y BETWEEN $y-25 AND $y+25)");
echo "<table border='1' align='center' cellpadding='5'>";
echo "<tr> <th>City Name</th> <th>X</th> <th>Y</th> </tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $res )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['cityname'] . '</td>';
echo '<td>' . $row['x'] . '</td>';
echo '<td>' . $row['y'] . '</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
试试这个:
$query="SELECT * FROM cityname
WHERE (x between".$_POST['search']."-25 AND ".$_POST['search']."+25)
AND (y between".$_POST['search']."-25 AND ".$_POST['search']."+25)";
当我告诉你这些的时候,请记住,以你现在的方式来做会让你更容易受到SQL注入的影响,并且你应该真正使用PDO或类似的方法来处理准备好的语句。话虽如此:
$x = (intval)$_POST['fld_x'];
$y = (intval)$_POST['fld_y'];
$res = mysql_query("select * FROM my_dbase WHERE (x between $x-25 AND $x+25) AND (y BETWEEN $y-25 AND $y+25)");
$data = array();
while($row = mysql_fetch_assoc($res)) {
$data[] = $row;
}
然后做你想做的$data
示例
编辑
为确保数据库连接正常,请在需要的地方更改/添加以下内容:
if(!mysql_select_db ("dbase")) {
die(mysql_error());
}
after after $res = mysql_query...
put:
if(!$res) {
die("Query Failed: ".mysql_error());
}
编辑
基于当前代码的完整代码:
前面显示的HTML为:
<form action="xysearch.php" method="get">
<label>X Coord
<input type="text" name="fld_x" />
</label>
<label>Y Coord
<input type="text" name=fld_y" />
</label>
<input type="submit" value="Search" />
</form>
, PHP是:
<?php
$x = (intval)$_POST['fld_x'];
$y = (intval)$_POST['fld_y'];
mysql_connect ("localhost","user","pass") or die (mysql_error());
mysql_select_db ("db");
$res = mysql_query("select * FROM table WHERE (x between $x-25 AND $x+25) AND (y BETWEEN $y-25 AND $y+25)");
echo "<table border='1' align='center' cellpadding='5'>";
echo "<tr> <th>City Name</th> <th>X</th> <th>Y</th> </tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $res )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['cityname'] . '</td>';
echo '<td>' . $row['x'] . '</td>';
echo '<td>' . $row['y'] . '</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
如果你想让圆的半径为25,你需要使用毕达哥拉斯定理
所以查询应该是
SELECT cityname, x, y FROM my_database
WHERE SQRT((x - centre_x) * (x - centre_x) + (y - centre_y) * (y - centre_y)) <=25
其中centre_x, centre_y是您输入的位置