justlukeyou Posted December 20, 2012 Share Posted December 20, 2012 Hi, I have search script which will only search one row at a time. The first two codes below work however the third fails to work but I am using the same code to query the two rows for the results string. Can anyone advise how search more than one row at a time? This searches firstname $where .= "`surname` LIKE '%$keyword%'"; This searches surname $where .= "`surname` LIKE '%$keyword%'"; This search fails $where .= "`firstname`, `surname` LIKE '%$keyword%'"; <?php function search_results ($keywords) { $returned_results = array(); $where = ""; $keywords = preg_split('/[\s]+/', $keywords); $total_keywords = count($keywords); foreach($keywords as $key=>$keyword) { $where .= "`surname` LIKE '%$keyword%'"; if ($key != ($total_keywords - 1)) { $where .= " AND "; } } $results = "SELECT `firstname`, `surname` FROM `users` WHERE $where"; $results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0; if ($results_num === 0) { return false; }else{ while ($results_row = mysql_fetch_assoc($results)) { $returned_results[] = array( 'firstname' => $results_row['firstname'], 'surname' => $results_row['surname'], ); Quote Link to comment Share on other sites More sharing options...
codefossa Posted December 20, 2012 Share Posted December 20, 2012 http://www.w3schools.com/sql/sql_and_or.asp Quote Link to comment Share on other sites More sharing options...
justlukeyou Posted December 20, 2012 Author Share Posted December 20, 2012 Thanks, When I try that it stops the code from working. foreach($keywords as $key=>$keyword) { $where .= "`firstname` AND `surname` LIKE '%$keyword%'"; if ($key != ($total_keywords - 1)) { $where .= " AND "; Quote Link to comment Share on other sites More sharing options...
codefossa Posted December 20, 2012 Share Posted December 20, 2012 You would check both. If you wanted to look for someone named James Howard, you could do .. `firstname` = 'James' AND `surname` = 'Howard' To search from the keyword, you would change the = '' to LIKE '%{$keyword}%' like you're doing. You just have to compare both, you don't choose two fields at the same time for comparing. Quote Link to comment Share on other sites More sharing options...
Jessica Posted December 20, 2012 Share Posted December 20, 2012 Still wrong. I know you know how to use and and or in a query, you've done it before. And those are columns, not rows. Quote Link to comment Share on other sites More sharing options...
justlukeyou Posted December 21, 2012 Author Share Posted December 21, 2012 Cheers dude. I have around 15 columns to search so it could get long! $where .= "`firstname` LIKE '%$keyword%' OR `surname` LIKE '%$keyword%'"; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.