我正在创建一个分页脚本,我需要获取数据库查询中的第一个和最后一个结果,以便我可以确定当用户单击要转到的页面时显示的结果。这是我在一分钟代码:如何从查询中获取第一个和最后一个结果?
// my database connection is opened
// this gets all of the entries in the database
$q = mysql_query("SELECT * FROM my_table ORDER BY id ASC");
$count = mysql_num_rows($q);
// this is how many results I want to display
$max = 2;
// this determines how many pages there will be
$pages = round($count/$max,0);
// this is where I think my script goes wrong
// I want to get the last result of the first page
// or the first result of the previous page
// so the query can start where the last query left off
// I've tried a few different things to get this script to work
// but I think that I need to get the first or last result of the previous page
// but I don't know how to.
$get = $_GET['p'];
$pn = $_GET['pn'];
$pq = mysql_query("SELECT * FROM my_table ORDER BY id ASC LIMIT $max OFFSET $get");
// my query results appear
if(!$pn) {
$pn = 1;
}
echo "</table><br />
Page $pn of $pages<br />";
for($p = 1;$p<=$pages;$p++) {
echo "<a href='javascript:void(0);' onclick='nextPage($max, $p);' title='Page $p'>Page $p</a> ";
}
**你的代码容易受到SQL注入的攻击**你应该使用准备好的语句,将你的变量作为参数传递给你,这些参数不会被SQL评估。如果你不知道我在说什么,或者如何解决它,请阅读[Bobby Tables](http://bobby-tables.com)的故事。 – eggyal
另外,请停止使用古老的MySQL扩展编写新代码:它不再被维护,并且社区已经开始[弃用过程](http://news.php.net/php.internals/53799)。相反,您应该使用改进的[MySQLi](http://php.net/mysqli)扩展或[PDO](http://php.net/pdo)抽象层。 – eggyal
目前尚不清楚问题是什么。 –