0

Im trying to run a simple search query to on all the fields in my contacts table. Basically want to look in all the fields in the contacts table for any match record that is passed in $valueToSearch. My code is below I'm getting error message -Im trying to run a simple search query to on all the fields in my contacts table. Is there a problem with the structure in my sql query ? Im new to PHP

$query = "SELECT  `firstName`, `lastName`, `nickName`, `cellNumber` , `workNumber` , `homeNumber` , `birthday` , `memo` FROM contacts LIKE '%".$valueToSearch."%'  WHERE userId = '{$_SESSION['user_id']}' ";
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
S. Thomas
  • 31
  • 1
  • 8
  • You need to specify what column the *WHERE* search will be done. Like (searching only the first and last name, add more *OR* clauses if needed): $query = "SELECT `firstName`, `lastName`, `nickName`, `cellNumber` , `workNumber` , `homeNumber` , `birthday` , `memo` FROM contacts WHERE (`firstname` LIKE '%".$valueToSearch."%' OR `lastNAME` LIKE '%".$valueToSearch."%' ) AND `userId` = '{$_SESSION['user_id']}' "; – Ernani Azevedo Oct 17 '18 at 03:46
  • thank you so much. That works. If I need the WHERE to search all columns in table , do I have to manually type back all the columns name ? or is there a more effective way to specify all columns ? – S. Thomas Oct 17 '18 at 03:53
  • 3
    Possible duplicate of [How to search multiple columns in MySQL?](https://stackoverflow.com/questions/2514548/how-to-search-multiple-columns-in-mysql) – Jay Bhatt Oct 17 '18 at 03:54

1 Answers1

-1

You can't put LIKE before WHERE clause and LIKE need to be placed after a column. Try this way:

$query = "SELECT  `firstName`, `lastName`, `nickName`, `cellNumber` , `workNumber` , `homeNumber` , `birthday` , `memo` FROM contacts WHERE userId = '{$_SESSION['user_id']}' AND `fieldYouWantToFilter` LIKE '%".$valueToSearch."%' ";
  • I didn't down vote this answer to a duplicate question, but keep in mind that if `$valueToSearch` is coming from a user submission or otherwise untrustworthy source, then this query is vulnerable to injection attacks and general query instability. – mickmackusa Oct 17 '18 at 04:12