两个选择语句的分页如何组合在一起?

时间:2011-07-22 05:08:06

标签: php javascript mysql

关于php查询:

<?php
$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if($_POST!=""){
$mydate = mysql_real_escape_string($_POST['datepicker']);
if($mydate!=""){    
$sql = "SELECT * FROM table WHERE date = '$mydate'";    
}       
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '')
{
if(mysql_num_rows($pg_result) > 0)
{
while($data = mysql_fetch_assoc($pg_result))
{ 
echo "
.......................
.......................
.......................
";
}        
echo "</br>". $pagination_output; 
}
else
{
echo "No Data.";
}
}
else
{
echo $pg_error; 
}
?>

Pagination.php

<?php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{   
if(empty($all_results))
{
$total_results = 0; 
}
else
{
$total_results = mysql_num_rows($all_results); 
}
$max_pages = ceil($total_results / $results_per_page);          
if(isset($_GET['page_id']))
{           
$page_id = (int) $_GET['page_id'];          
if($page_id > $max_pages || empty($page_id))
{
$page_id = 1;               
}
}
else
{
$page_id = 1;           
}
$page_id_temp = ($page_id - 1) * $results_per_page;
$sql_offset = $page_id_temp;
$user_sql .= " limit $sql_offset, $results_per_page";       
$pg_result = mysql_query($user_sql);
Create_Links();
}
else
{
$pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
?>

对于第一个查询分页工作正常($ today select)。但是对于第二个($ mydate select)不能正常工作。它的agian今天选择。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以执行UNION将SQL语句合并到一个结果集中并对其使用分页。

http://dev.mysql.com/doc/refman/5.0/en/union.html

$today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if($_POST!=""){
$mydate = mysql_real_escape_string($_POST['datepicker']);
if($mydate!=""){    
$sql = "SELECT * FROM table WHERE date = '$mydate'";    

可以:

$today = date('D, d M, Y');
if($_POST!=""){
$mydate = mysql_real_escape_string($_POST['datepicker']);
if($mydate!=""){    
$sql = "SELECT * FROM table WHERE date = '$mydate' UNION SELECT * FROM table WHERE date = '$today'";