Salman Razak Memon
Salman Razak Memon

Reputation: 93

mysql select query search one word in multiple columns

Help is required. i am preparing a search form. need help in select query is it possible that i can search "building" word in all columns of my table following is the query i've tried.

$search = $_POST['search'];
$sql = mysql_query("SELECT * FROM property WHERE posthead,requestto,ptype,requestby,owner,bed,bath,price,sqft,descp = '".$search."'");
$result = (mysql_fetch_array($sql));

echo "Post Head : ". $result['posthead']."<br />";
echo "Request To : ". $result['requestto']."<br />";
echo "Type : ". $result['ptype']."<br />";
echo "Request By : ". $result['requestby']."<br />";
echo "Owner : ". $result['owner']."<br />";
echo "Bed : ". $result['bed']."<br />";
echo "Bath : ". $result['bath']."<br />";
echo "Price : ". $result['price']."<br />";
echo "Sq ft. : ". $result['sqft']."<br />";
echo "Description : ". $result['descp']."<br />";

Upvotes: 1

Views: 4196

Answers (4)

DWX
DWX

Reputation: 2340

TRY THIS:

Better is to use "CONCAT" for the columns:

$sql = mysql_query("SELECT * FROM property WHERE CONCAT(posthead,requestto,ptype,requestby,owner,bed,bath,price,sqft,descp) LIKE "%.$search."%'");

OR will work but CONCAT can reduce query size.

Upvotes: 1

peterm
peterm

Reputation: 92785

Since you are creating a searching form you might want to be able to find records by partial match and not exact word. In order to do that you can use LIKE

$q = "SELECT * FROM property 
WHERE posthead  LIKE '%$search%' OR
      requestto LIKE '%$search%' OR
      ptype     LIKE '%$search%' OR
      requestby LIKE '%$search%' OR
      owner     LIKE '%$search%' OR
      bed       LIKE '%$search%' OR
      bath      LIKE '%$search%' OR
      price     LIKE '%$search%' OR
      sqft      LIKE '%$search%' OR
      descp     LIKE '%$search%'";

$sql = mysql_query($q);

Upvotes: 0

afarazit
afarazit

Reputation: 4984

Try SELECT * FROM property WHERE posthead = $search OR requestto = $search ... etc

Upvotes: 0

Prasanth Bendra
Prasanth Bendra

Reputation: 32740

$sql = mysql_query("SELECT * FROM property WHERE posthead = '".$search."' OR requestto= '".$search."' OR ptype= '".$search."' OR requestby = '".$search."' OR owner= '".$search."' OR bed = '".$search."' OR bath= '".$search."' OR price= '".$search."' OR sqft,descp = '".$search."'");

and change $result = (mysql_fetch_array($sql)); to $result = (mysql_fetch_assoc($sql));

NOTE :

  1. your query is vulnerable to sql injection
  2. mysql_* functions are deprecated use mysqli_* or PDO

Upvotes: 2

Related Questions