在PHP中搜索多个字段的函数

时间:2014-05-29 05:14:53

标签: php mysql search

我正在PHP MySQL中创建一个Search函数。目前,我的代码正在运行,但在尝试按日期搜索时,会显示所有内容。这两个字段似乎没有连接。

请帮忙。感谢。

<?php
$query = $_GET['query']; 
$date = $_GET['date']; 

// gets value sent over search form


    $query = htmlspecialchars($query); 
    // changes characters used in html to their equivalents, for example: < to &gt;

    $query = mysql_real_escape_string($query);
    // makes sure nobody uses SQL injection



    $raw_results = mysql_query("SELECT * FROM tblArchive WHERE (Author LIKE '%".$query."%' OR Title LIKE '%".$query."%' or Content LIKE '%".$query."%' AND Date LIKE '%".$date."%')");


    if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following

        while($results = mysql_fetch_array($raw_results)){
        // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

            echo "<p><h3>".$results['Title']."</h3>"."<h3>".$results['Author']."</h3>"."<h4>".$results['Date']."</h4>".$results['Content']."</p>";
            // posts results gotten from database(title and text) you can also show id ($results['id'])
        }

    }
    else{ // if there is no matching rows do following
        echo "No results";
    }

&GT;

2 个答案:

答案 0 :(得分:0)

    $raw_results = mysql_query(
"SELECT * FROM tblArchive 
WHERE (Author LIKE '%".$query."%' 
OR Title LIKE '%".$query."%' or Content LIKE '%".$query."%') 
AND (Date LIKE '%".$date."%')");

请尝试此查询它会正常工作。

答案 1 :(得分:0)

     $get = 'SELECT * FROM tblArchive';

     if(!empty($query)){

     $get .= ' WHERE (Author LIKE '%".$query."%' OR Title LIKE '%".$query."%' or Content LIKE '%".$query."%' ';

    }

    if(!empty($date) && !empty($query)){

     $get .= " And Date LIKE '%".$date."%'";
     }
     else{

     $get .= " Where Date LIKE '%".$date."%'";
     }

    $result = mysql_query($get);