Kinyanjui Kamau
Kinyanjui Kamau

Reputation: 1936

how to build PHP/MySQL query to input data from a series of checkboxes

I am making a website that will show night club revelers events and night establishments in a big city.

A user should be able to add certain details when adding their event on the site e.g.(in the events table) event_id, event_name, event_description, event_date, event_photo_url etc.

I want users to be able to search or find certain events or establishments based on interests. I have an interest table that looks like this.

interest_id, interest-name
1, Shoot Pool
2, Karaoke
3, Lounge
4, Live Band
5, Dancing
6, Watch Sports

So there are 6 checkboxes on my form. A user can select none, 1, 2 or all 6.

Should I have each checkbox submit individual values to my submit form, ie

input name="dancing" type="checkbox" value="5" 
input name="watch_sports" type="checkbox" value="6"

Or should I build an array

input name="interest[]" type="checkbox" value="5" 
input name="interest[]" type="checkbox" value="6" 

I have a table to link events with interests ie;

event_interest table  
event_interest_id            
event_id              
interest_id 

I have never implemented a series of check boxes before. Does anyone know the way to go about capturing user input and storing the values in my database?

Upvotes: 1

Views: 373

Answers (1)

helle
helle

Reputation: 11650

you will get as POST or GET those checkbox values which are checked.

so u can do something like:

$interests = $_POST['interests'];
$event_id = intval($_POST['event_id']);//or where ever you get that from
foreach($interests as $interest){
    ....
    $interest = intval($interest);
    $query = "INSERT INTO event_interests  SET interest_id = $interest, event_id = $event_id";
    .... //send query to db
}

Upvotes: 1

Related Questions