jonathanl5660
jonathanl5660

Reputation: 161

PHP - Do a search using two search terms from two drop-down menus

I am trying to use two drop-down boxes to search my database. ($k) Services and ($t) for Town. But only one of the term is working I'm new too PHP. I know I'm know using mysqli I just want to get it working and update this later.

$k = $_GET['k'];
$t = $_GET['t'];

$i = 0;
$term1 = explode(" ", $k);
$term2 = explode(" ", $t);

$result = array_merge($term1, $term2);

$query ="SELECT * FROM clients WHERE "; 

foreach ($result as $each) {
    $i++;
    if ($i == 1)
        $query .= "company_services LIKE '%$each%'" . "OR town LIKE '%$each%'";
}
$dbconnect=@mysql_connect($mysql_host, $mysql_user, $mysql_password);
$db = mysql_select_db('db_name');

$query = mysql_query($query) or die(mysql_error());;
$numrows = mysql_num_rows($query);
if ($numrows > 0){

    while ($row = mysql_fetch_assoc($query)) {

Upvotes: 2

Views: 42

Answers (2)

Professor Abronsius
Professor Abronsius

Reputation: 33813

Perhaps something like this might work?

if( isset( $_GET['k'], $_GET['t'] ) ){

    $term1 = explode( " ", $_GET['k'] );
    $term2 = explode( " ", $_GET['t'] );

    $result = array_merge( $term1, $term2 );
    $clauses=array();

    $query ="select * from `clients`"; 

    foreach( $result as $word ) {
        $clauses[]="( `company_services` like '%$word%' OR `town` like '%$word%' )";
    }

    $query = !empty( $clauses ) ? $query . ' where ' . implode(' or ',$clauses ) : $query;


    $dbconnect=@mysql_connect( $mysql_host, $mysql_user, $mysql_password );
    $db = mysql_select_db( 'db_name' );

    $query = mysql_query( $query ) or die( mysql_error() );
    $numrows = mysql_num_rows( $query );


    if ($numrows > 0){
        while ($row = mysql_fetch_assoc($query)) { 
            /* do stuff*/
        }
    }
}

Upvotes: 3

Henrik
Henrik

Reputation: 189

$result = array_merge($term1, $term2);
This will set $result to an array of values. At the moment you are just using the first value of the $result-array. Change your foreach loop to this to use all the values:

foreach ($result as $each) {
  $query .= "company_services LIKE '%$each%' OR town LIKE '%$each%' ";
}

Upvotes: 0

Related Questions