php 站内搜索 多表 分页

时间:2021-12-08 23:55:35

借鉴了:http://blog.chinaunix.net/uid-20787846-id-3488253.html 这篇文章 ,在此基础上增加了分页功能

<?php
 /* 关键字 */
$keyword = trim($_REQUEST['title']);
if(!empty($keyword))
{
      $str = "";
      $count = '';
      /* 搜索表名称 */
      $arr = array("channel"=>'`title`,`content`',"news"=>'`news_title`,`content`',"products"=>'`p_name`,`content`');

      foreach($arr as $key=>$value){
           $row = explode(",",$value);
           $title = str_replace("`","",$row[0]);
           $content = str_replace("`","",$row[1]);
           $sql_l = "SELECT * FROM ".$key." ";

       for($i=0;$i<count($row);$i++){
            $sql_l .= ( preg_match('/WHERE/i' , $sql_l ) ? ' or ': ' WHERE ' ).$row[$i]." like '%".$keyword."%' ";
       }

       $queryu = $sql->query($sql_l)or die(mysql_error());

       while($site = $sql->assoc($queryu)){

             $title2 = str_ireplace($keyword, "<font color='red'>".$keyword."</font>",$site[$title]);
             $content2 = str_ireplace($keyword, "<font color='red'>".$keyword."</font>", cut_str(strip_tags($site[$content]),180));

        switch($key){
        case 'channel':
        $href = "GroupCEO.php?pid=3&cid=".$site['id'];
        break;
        case 'news':
        $href = "Newslist.php?pid=4&xwid=".$site['id'];
        break;
        case 'products':
        $href = "product_read.php?pid=1&fid=".$site['fid']."&id=".$site['id'];
        break;

       }
        $str .= '<p class="hei"><strong class="lan"><a href="'.$href.'">'.$title2.'</a></strong>'.$content2.'</p<div style=" border-bottom:#666 dashed 1px;height:1px;"></div>';
       $count  .= "1";

       }
      }
       //分页
        $array = explode("   ", $str);

        $page = $_REQUEST['page']?(int)$_REQUEST['page']:1;
        $totalRows = strlen($count);
        $pageSize=12;
        $totalPage=ceil($totalRows/$pageSize);
        if($page<1||$page==null||!is_numeric($page))$page=1;
        if($page>=$totalPage)$page=$totalPage;

        $start = ($page-1)*$pageSize;
        $end = $page*$pageSize;

    }

        if(empty($str))
        {
            echo "<div style='margin:20px' >对不起!您搜索的内容不存在!</div>" ;
        }
        else
        {
            for($i=$start;$i<$end;$i++)
            {
                echo $array[$i];
            }
        }

    }
    else
    {
            echo "<div style='margin:20px' >对不起!您搜索的内容不存在!</div>" ;
    }
?>

<div align="center" style="font-size:15px"><?php echo showPage($page, $totalPage,"keyword=$keyword");?></div>

  

以上内容仅提供思路 。