Mensur
Mensur

Reputation: 475

simple php mysql search engine with checkboxes

I would like to do a search engine for my webpage. I have several tables in my mysql database and i would like them combined when user

Table users
id  name        age country     vip profile_image
1   nick        23  sweden      1   yes
2   michael     20  germany     0   no
3   laura       19  usa         1   yes
4   gary        33  china       1   yes

Table online
id  user_id     online
1   1             1
2   2             1 
3   4             1

user_id is connected to id in users table

Now i have checkboxes
[ ] Those which are online
[ ] Those which are vip
[ ] Those with profile image

Im coding my page in PHP and im trying to figure how to include certain searches in a sql query if certain checkbox is checked. I can have tons of options here. Example if no checkbox is checked, iff on you want to search for those which are online, how do i go in to the second table?

I hope you get my point here. I really hope someone could help me and give me an working example of the php & sql query.

Cheerz!

Upvotes: 0

Views: 2153

Answers (2)

Expedito
Expedito

Reputation: 7805

You need to form a query something like the following:

SELECT users.name, users.age, users.country
FROM users
LEFT JOIN online ON user.id = online.user_id
WHERE ((user.vip = 1) && (online.online = 1))

Upvotes: 0

TCFDS
TCFDS

Reputation: 622

First you have to check which checkboxes have been checked. Then you must write MySQL-query with PHP based on that information. You must think in every checkbox, what information it needs to check. If your database is well written, there is seldom a problem that two options affect each other. If information is in users-table, you need just write line to where-clause. If you need to join table to users-table to get information you need to do that too. Here is an example

$query = "";
$query .= "SELECT users.* FROM users";
if ($include_online == 1) {
  $query .= " LEFT JOIN online ON online.user_id = users.id";
}
$query .= " WHERE";
if ($include_vip == 1) {
 $query .= " users.vip = 1 AND";
}
if ($include_image == 1) {
  $query .= " users.profile_image = 'yes' AND";
}
if ($include_online == 1) {
  $query .= " online.online = 1 AND";
}
$query .= " users.name LIKE '%".$search_string."%'";

Upvotes: 1

Related Questions