user3523177
user3523177

Reputation: 51

Search multiple words and single word at a time in a multiple row in Mysql php

I'm trying to use this search for searching more than one words or single word at a time from a database. Now the problem is that my script only running properly but please help me...

 <form name="ds" method="post">
<input type="text" name="name" placeholder="Entername" />&nbsp;&nbsp;
<!--<input type="text" name="search" placeholder="Location" />-->
<select name="location[]" multiple="multiple">

<option value="delhi">Delhi</option>
<option value="Mumbai">Mumbai</option></select>
<input type="submit" name="submit" value="Search" />
</form>
<?
$conn=mysql_connect("localhost","root","");
mysql_select_db("dbrozgarexpress",$conn);
echo $search =$_POST['location'];
$description = "";
$name2=$_POST['name'];
if(isset($name2)&&$name2 != ""){
if($flag){
$cheack.= "AND ";
}
$cheack.="user_first_name ='$name2' ";
$flag =true;
}


if(isset($search)&&$search != ""){
if($flag){
$cheack.= "AND ";
}
foreach($search AS $s)
{
$cheack.="user_current_location_id ='$s' or ";
$flag =true;
}
}

$cheack = substr($cheack, 0, -4);
echo $query = "SELECT * FROM `tb_user` WHERE $cheack ";
?>
error SELECT * FROM `tb_user` WHERE user_first_name ='kum 

Upvotes: 0

Views: 194

Answers (1)

Latheesan
Latheesan

Reputation: 24116

I think I have a general idea of what you are after.

P.S. the query will only show after you submit the form - i.e. after you click search button

Try this:

<?php

// Handle Post
if (count($_POST))
{
    // Load Params
    $name = isset($_POST['name']) ? $_POST['name'] : '';
    $locations = isset($_POST['location']) ? $_POST['location'] : array();

    // Start Query
    $sql = 'SELECT * FROM `tb_user` WHERE ';

    // Build Query
    $sql_parts = array();
    if (!empty($name)) {
        $sql_parts[] = "`user_first_name` = '$name'";
    }
    if (sizeof($locations)) {
        foreach ($locations as $location) {
            $sql_parts[] = "`user_current_location_id` = '$location'";
        }
    }
    $sql = $sql . implode(' AND ', $sql_parts);

    // Debug
    echo $sql ."<br><br>";
}

?>

<form action="" name="ds" method="post">
<input type="text" name="name" placeholder="Entername" />&nbsp;&nbsp;
<select name="location[]" multiple="multiple">
<option value="delhi">Delhi</option>
<option value="Mumbai">Mumbai</option></select>
<input type="submit" name="submit" value="Search" />
</form>

Here's an example of this working:


No location selected, name only

enter image description here


name and one location

enter image description here


name and two location

enter image description here

Upvotes: 1

Related Questions