嘿,我想添加一个按钮(链接),单击该按钮将过滤分页结果。
我是php(和一般编程)的新手,想添加一个像'Automotive'这样的按钮,点击它时会更新我的分页脚本中的2个mysql查询,如下所示:
正如您所看到的,汽车类别是硬编码的,我希望它是动态的,因此当点击链接时,它会将查询的类别部分中的id或类放置。
1:
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='automotive'"));
2:
$get = mysql_query("SELECT * FROM explore WHERE category='automotive' LIMIT $start, $per_page");
这是我正在使用的整个当前的php分页脚本:
<?php
//connecting to the database
$error = "Could not connect to the database";
mysql_connect('localhost','root','root') or die($error);
mysql_select_db('ajax_demo') or die($error);
//max displayed per page
$per_page = 2;
//get start variable
$start = $_GET['start'];
//count records
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='automotive'"));
//count max pages
$max_pages = $record_count / $per_page; //may come out as decimal
if (!$start)
$start = 0;
//display data
$get = mysql_query("SELECT * FROM explore WHERE category='automotive' LIMIT $start, $per_page");
while ($row = mysql_fetch_assoc($get))
{
// get data
$name = $row['id'];
$age = $row['site_name'];
echo $name." (".$age.")<br />";
}
//setup prev and next variables
$prev = $start - $per_page;
$next = $start + $per_page;
//show prev button
if (!($start<=0))
echo "<a href='pagi_test.php?start=$prev'>Prev</a> ";
//show page numbers
//set variable for first page
$i=1;
for ($x=0;$x<$record_count;$x=$x+$per_page)
{
if ($start!=$x)
echo " <a href='pagi_test.php?start=$x'>$i</a> ";
else
echo " <a href='pagi_test.php?start=$x'><b>$i</b></a> ";
$i++;
}
//show next button
if (!($start>=$record_count-$per_page))
echo " <a href='pagi_test.php?start=$next'>Next</a>";
?>
答案 0 :(得分:0)
包含2个链接/类别的示例:
<a href='script.php?category=automotive'>automotive</a> <a href='script.php?category=sports'>sports</a>
Inside script.php:
$category = mysql_real_escape_string($_GET['category']);
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='$category'"));
...
$get = mysql_query("SELECT * FROM explore WHERE category='$category' LIMIT $start, $per_page");
答案 1 :(得分:0)
编辑:我只是发布了这个答案,以回应OP说他不熟悉编程。良好的卫生习惯在一开始就很容易学习,成为习惯,或者很晚以后很难养成习惯。
http://us2.php.net/manual/en/security.database.sql-injection.php
另请阅读有关数据库安全性的文章。将查询编写为:
会有很大改进$start = mysql_real_escape_string($_GET['start']);
settype($start, 'integer');
$category = mysql_real_escape_string($_GET['category']);
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='%s'", $category));
...
$get = mysql_query("SELECT * FROM explore WHERE category='%s' LIMIT %d, %d", $category, $start, $per_page);
编写额外的安全代码总是值得的,即使只是为了练习。数据库的基本安全规则是:永远不要信任用户输入,始终检查生成的输出。由于输入来自查询字符串并且针对数据库运行,因此必须对其进行过滤。