我有一个分页代码,我在网上找到了。代码工作得非常好,因为查询是硬编码的,但我很难弄清楚如何将搜索查询发布到页面并逐步完成结果。
例如,我想使用带有两个文本字段年龄和性别的搜索表单;将查询发送到脚本并逐个执行结果。 这是脚本;
<?php
?>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>paging script in PHP</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
<?php
require "config.php"; // All database details will be included here
$theBreed = NULL;
$page_name="testpage.php"; // If you use this code with a different page ( or file ) name then change this
// To take care global variable if OFF
$start=$_GET['start'];
if(!($start > 0)) { // This variable is set to zero for the first page
$start = 0;
}
$eu = ($start -0);
$limit = 1; // No of records to be shown per page.
$this1 = $eu + $limit;
$back = $eu - $limit;
$next = $eu + $limit;
/////////////// WE have to find out the number of records in our table. We will use this to break the pages///////
$query2="SELECT * FROM students";
$result2=mysql_query($query2);
echo mysql_error();
$nume=mysql_num_rows($result2);
/////// The variable nume above will store the total number of records in the table////
/////////// Now let us print the table headers ////////////////
$bgcolor="#f1f1f1";
echo "<TABLE width=50% align=center cellpadding=0 cellspacing=0> <tr>";
echo "<td bgcolor='dfdfdf' > <font face='arial,verdana,helvetica' color='#000000' size='4'>ID</font></td>";
echo "<td bgcolor='dfdfdf' > <font face='arial,verdana,helvetica' color='#000000' size='4'>Name</font></td>";
echo "<td bgcolor='dfdfdf' > <font face='arial,verdana,helvetica' color='#000000' size='4'>Sex</font></td>";
echo "<td bgcolor='dfdfdf'> <font face='arial,verdana,helvetica' color='#000000' size='4'>Breed</font></td></tr>";
////////////// Now let us start executing the query with variables $eu and $limit set at the top of the page///////////
$query=" SELECT * FROM students limit $eu, $limit ";
$result=mysql_query($query);
echo mysql_error();
//////////////// Now we will display the returned records in side the rows of the table/////////
while($noticia = mysql_fetch_array($result))
{
if($bgcolor=='#f1f1f1'){$bgcolor='#ffffff';}
else{$bgcolor='#f1f1f1';}
echo "<tr >";
echo "<td align=left bgcolor=$bgcolor id='title'> <font face='Verdana' size='2'>$noticia[id]</font></td>";
echo "<td align=left bgcolor=$bgcolor id='title'> <font face='Verdana' size='2'>$noticia[name]</font></td>";
echo "<td align=left bgcolor=$bgcolor id='title'> <font face='Verdana' size='2'>$noticia[sex]</font></td>";
echo "<td align=left bgcolor=$bgcolor id='title'> <font face='Verdana' size='2'>$noticia[breed]</font></td>";
echo "</tr>";
}
echo "</table>";
////////////////////////////// End of displaying the table with records ////////////////////////
///// Variables set for advance paging///////////
$p_limit=10; // This should be more than $limit and set to a value for whick links to be breaked
$p_f= 0;
$p_f=$_GET['p_f']; // To take care global variable if OFF
if(!($p_f > 0)) { // This variable is set to zero for the first page
$p_f = 0;
}
$p_fwd=$p_f+$p_limit;
$p_back=$p_f-$p_limit;
//////////// End of variables for advance paging ///////////////
/////////////// Start the buttom links with Prev and next link with page numbers /////////////////
echo "<table align = 'center' width='50%'><tr><td align='left' width='20%'>";
if($p_f<>0){print "<a href='$page_name?start=$p_back&p_f=$p_back'><font face='Verdana' size='2'>PREV $p_limit</font></a>"; }
echo "</td><td align='left' width='10%'>";
//// if our variable $back is equal to 0 or more then only we will display the link to move back ////////
if($back >=0 and ($back >=$p_f)) {
print "<a href='$page_name?start=$back&p_f=$p_f'><font face='Verdana' size='2'>PREV</font></a>";
}
echo "</td><td align='right' width='10%'>";
///////////// If we are not in the last page then Next link will be displayed. Here we check that /////
if($this1 < $nume and $this1 <($p_f+$p_limit)) {
print "<a href='$page_name?start=$next&p_f=$p_f'><font face='Verdana' size='2'>NEXT</font></a>";}
echo "</td><td align='right' width='20%'>";
if($p_fwd < $nume){
print "<a href='$page_name?start=$p_fwd&p_f=$p_fwd'><font face='Verdana' size='2'>NEXT $p_limit</font></a>";
}
echo "</td></tr></table>";
?>
</body>
</html>
任何帮助都将不胜感激。
答案 0 :(得分:0)
出于安全原因,您不希望向该页面发布查询,最好将查询放在该页面上的代码中,然后使用您的帖子发送一些信息以调用搜索。
让我们从查询开始吧。如果您想根据年龄和性别进行查询,可以使用以下内容:
$query2 = "SELECT * FROM students WHERE Age >= $min_age AND Age <= $max_age AND Sex = '$sex'";
$query = "SELECT * FROM students WHERE Age >= $min_age AND Age <= $max_age AND Sex = '$sex' LIMIT $eu, $limit";
现在您需要更新PHP脚本以处理4个新参数:
第四个参数(action)将用于指定我们要执行搜索,而不是使用返回所有结果的现有查询。
现在更新代码。请注意,您只需添加一些额外费用即可:
首先处理您的POST变量并对有效值应用一些检查以防止SQL注入攻击:
$min_age = $_POST['min_age'];
$max_age = $_POST['max_age'];
$sex = $_POST['sex'];
if(!is_numeric($min_age) || $min_age < 0 || !is_numeric($max_age) || $max_age < 0 || ($sex != 'm' && $sex != 'f'))
throw new Exception("Invalid parameters passed");
接下来,将$ query2查询包装在条件语句中,这样如果我们正在进行搜索,我们可以使用修改后的版本进行搜索:
if(isset($_POST['action']) && $_POST['action'] == 'search')
{
//Doing a search
$query2 = "SELECT * FROM students WHERE Age >= $min_age AND Age <= $max_age AND Sex = '$sex'";
}
else
{
/////////////// WE have to find out the number of records in our table. We will use this to break the pages///////
$query2="SELECT * FROM students";
}
现在对页面下方的主查询进行类似的更改
if(isset($_POST['action']) && $_POST['action'] == 'search')
{
$query = "SELECT * FROM students WHERE Age >= $min_age AND Age <= $max_age AND Sex = '$sex' LIMIT $eu, $limit";
}
else
$query=" SELECT * FROM students limit $eu, $limit ";
}
它负责PHP的结束。现在剩下的就是创建搜索表单并添加一个包含操作的隐藏字段:
<form method="post" action="yourphpfile.php">
<input type='hidden' name='action' value='search'/>
Min Age: <input type='text' name='min_age'/>
Max Age: <input type='text' name='max_age'/>
Sex: <select name='sex'><option value='f'>Female</option><option value='m'>Male</option></select>
</form>
简而言之,这就是基础知识。现在注意:上面的代码有一些类型检查,以确保插入到您的SQL语句中的数据不是恶意的,但我强烈建议您阅读SQL注入攻击并进行必要的进一步更改以确保安全
编辑:在类型检查中添加以防止SQL注入。
希望有所帮助。
答案 1 :(得分:0)
您可以使用SQL_CALC_FOUND_ROWS(如here所述),这是一种漂亮而又整洁的分页方法。
所以你可以做到以下几点:
<?php
// make sure you sanitize your inputs!
$age = $_GET['age'];
$sex = $_GET['sex'];
$rows = 10; // change to whatever number of rows you need.
$page = empty( $_GET['page'] ) ? 1 : $_GET['page'];
$page = $page < 1 ? 1 : $page;
$page = (--$page) * $rows;
$qry = "SELECT SQL_CALC_FOUND_ROWS * FROM students
WHERE age = :age
AND sex = :sex
LIMIT :page, :rows;";
$db = new PDO('mysql:dbname=yourdb:host=localhost', $username, $password);
$srch = $db->prepare($qry);
$srch->bindValue( ':age' , $age, PDO::PARAM_INT );
$srch->bindValue( ':sex' , $sex, PDO::PARAM_STR );
$srch->bindValue( ':page' , $page, PDO::PARAM_INT );
$srch->bindValue( ':page' , $rows, PDO::PARAM_INT );
$srch->execute();
$results = $srch->fetchAll( PDO::FETCH_ASSOC );
$number = $db->query('SELECT FOUND_ROWS() AS `pages`;');
$pageNum = $number->fetch( PDO::FETCH_ASSOC );
// start building your pagination.
$url = '?age='.$age.'&sex='.$sex.'&page=';
for( $i = 1 ; $i <= $pageNum['pages'] ; $i++ )
{
if( $i == $page )
{
echo '<span>'.$i.'</span> >';
}
else
{
echo '<a href="'.$url.$i.'">'.$i.'</a> >';
}
}
// your form code.
// you result listing.