简体   繁体   中英

Search function for multiple fields in PHP

I am making a Search function in PHP MySQL. Currently, my code is working but when trying to search by date, all content appear. It seems that the 2 fields aren't connected.

Please help. Thanks.

<?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";
    }

?>

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

Please Try This Query It will work fine.

     $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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM