开发者

Select row from DB based on 3 different values

开发者 https://www.devze.com 2023-03-17 10:16 出处:网络
Currently my DB looks similar too... IDUsernameInterest 04TommySoccer 04TommyInternet 32JackSoccer 32JackSwimming

Currently my DB looks similar too...

ID     Username     Interest
04     Tommy        Soccer
04     Tommy        Internet
32     Jack         Soccer
32     Jack         Swimming
32     Jack         Boxing

I have a page on my website where the user can specify his/her interests and depending on what they enter, those with the same interests will be displayed.

So If Tommy was to visit my page and add "Boxing" as an Interest Jack would show up as he has "Boxing" listed within the table.

I need to write a query to do this but i'm unsure of the best way to do it as i'm still very new to PHP, would something along the 开发者_如何学JAVAlines of...

mysql_query(SELECT * FROM interests_table WHERE Interest = $interest1 || $interest2 || Interest3);


mysql_query("SELECT * FROM interests_table WHERE (Interest = $interest1 OR Interest = $interest2 OR Interest = $Interest3)");


Even shorter:

mysql_query("SELECT * FROM interests_table WHERE Interest IN ($interest1, $interest2, $interest3)");

Of course you will need to add necessary parameters escaping for more secure code.

If you have all possible values you want to search for in array, the code may look like this:

$interests = array('boxing', 'swimming', 'speedway');
// ... query preparation
$result = mysql_query("SELECT * FROM interests_table WHERE Interest IN (" . implode('", "', mysql_real_escape_string($interests)) . ")");
// rest of the code ...

But this code is only effective for small sets of data (few to hundreds). If you'd have more interests on list, you should find more effective way.

0

精彩评论

暂无评论...
验证码 换一张
取 消