Vilarix
Vilarix

Reputation: 735

How to make an SQL query from form checkboxes?

I have two questions, simply for logic:

I need a database with video games (name, cover, description, platform, genre)

How can I make it so the Genre can have multiple values?

For example: Fallout 3 is FPS / RPG but I want to be able to display it if I make a query for FPS only or RPG only. Or simply have a page genre.php?genre=FPS which shows all FPS (with FPS/RPG or FPS/MMO games)

Is a query with LIKE enough?

And second question:

I have a form with different checkboxes for platforms which sends this to the PHP search script:

search.php?q=dead+island&PC=on&PS3=on&Xbox360=on&Wii=on

How can I create the SQL query without having to write it for all possibilities? Knowing that there are a lot of platform (NES, N64 etc.)

Example (simplified):

if(PC=on) = SQL search in platform PC

if(PC=on and PS3=on) = SQL search in platform PC and PS3

Thanks for your help!

Upvotes: 0

Views: 1034

Answers (1)

progrrammer
progrrammer

Reputation: 4489

For the first one: You can have many options for that,

  • If the genre field contains at most 2 value you can use 2 field (genre1,genre2) in creating a table.
  • You can create a separate table (with foreign key of games) for genre if one to many(can be more than 2) relationship exists betn games and genre.
  • Or, as you say use LIKE '%str%' // better if atmost 2 values

For the second:

Create a Query string as, [this sample is in php]

$sql="Select * from table_name where";
if($_Get['pc']=="on"){
    $sql+=" platform='pc' OR ";    
}

if($_Get['ps3']=="on"){
    $sql+=" platform='ps3' OR";    
    }
// and so on for as many conditions
// at last
$sql+=" 0; "; // This line is necessary because of use of 'OR' before

Hope This Helps!!

Upvotes: 4

Related Questions