1

I am trying to write a simple search function that reads in a string $query.

my question is, can I use multiple ORs in a select statement? I am trying to search one string to see if it matches many column values, then print those rows.

function search($query) {
   try {
     $db = db_open();

     $sql = "select * from pms where (name like :query) or (state like :query) or 
             (start like :query) or (finish like :query) ";

     $statement = $db->prepare($sql);
     $statement->bindValue(':query', $query);
     $statement->execute();
     $pms = $statement->fetchAll();

   } catch(PDOException $e) {
     die("Error: ".$e->getMessage());
     }
   return $pms;
   }

This is not working, except when i search for a state.

Thanks

AngeKing
  • 69
  • 6
  • solved, incorrect syntax in the binding statement. `$statement->bindValue(':query', $query);` should be: `$statement->bindValue(':query', "%$query%");` thanks to the other members for posting suggestions. They helped in tidying up my code anyway :-) – AngeKing Apr 09 '14 at 10:55

2 Answers2

0

For sure.

SELECT * FROM pms WHERE (name LIKE :query) OR (start LIKE :query) OR (finish LIKE :query)

Should work just fine.

Jonas m
  • 2,646
  • 3
  • 22
  • 43
  • no this didn't work :-(. still only the state is working. I will post the whole function, maybe I have something else wrong. – AngeKing Apr 09 '14 at 08:24
0

1) use backtick in table nam eand column names.
2) use bracket for each or for more clear understanding
3)if you are not using binding then use wildcat (%) with quotes . try like this:

$sql = "select * from `pms` 
where (`name` like '%query%') 
OR (`state` like '%query%') 
OR (`start` like '%query%') 
OR  (`finish` like '%query%') ";
Awlad Liton
  • 9,366
  • 2
  • 27
  • 53
  • thanks for the response. this still didn't work. it only works when i use: `$sql = "select * from pms where name like '%$query%' or state like '%$query%' or start like '%$query%' or finish like '%$query%'";` – AngeKing Apr 09 '14 at 08:29
  • i thought you are binding your query. okay i am updating my answer. If it helps then you should accept my answer :) – Awlad Liton Apr 09 '14 at 09:09