I have a database which takes user submitted data, the entries from which I want to group under one or several of about 10 categories.
So for example, you add your entry to my site, say its all about your business (a car valeting service), and I offer you the opportunity to categorize your entry in any number of 10 fixed categories (automotive, mobile service, etc), so if a user searches for businesses under the ‘automotive’ or ‘mobile service’ category, your business is returned from the query.
So as I have taken from most of the answers on here, to achieve this I have my database with three tables (structure below), one for your business entry, one listing the set categories, and one relational table to which I’ve added the unique key from the prior two tables.
CREATE TABLE `business` (
`bus_id` INT NOT NULL AUTO_INCREMENT,
`bus_name` VARCHAR(50) NOT NULL,
`bus_dscpn` TEXT NOT NULL,
`bus_url` VARCHAR(255) NOT NULL,
PRIMARY KEY (`bus_id`)
)
CREATE TABLE `categories` (
`category_id` INT NOT NULL AUTO_INCREMENT,
`category_name` VARCHAR(20) NOT NULL,
PRIMARY KEY (`category_id`)
)
CREATE TABLE `tbl_works_categories` (
`bus_id` INT NOT NULL,
`category_id` INT NOT NULL
)
What I cannot figure out for the life of me is, when you select which categories you’d like your business associated with from my form which is processed with PHP, how to actually associate them in the database!
I assume your form returns the category IDs for each category selected and that those IDs correspond with category_id in your categories table.
First you insert your business record into your business table, this will give you the auto increment number (mysql_insert_id function in PHP or whatever function for the library you are using). So, you have an
$idfromfunctionsomewhere stored.With that business ID, then loop through your category IDs
(perhaps already having used):
(… and showed this list to your user through checkboxes or drop list or whatever)
After the user chooses one
$categoryidfromform, you can then insert into your tbl_works_categories table