php - Selecting multiple fields from <option> and adding them to database -
background:
i creating 3 tier e commerce website sells books. within website have created form (only accessible staff members) allows staff member add new book system (the database).
at moment have table within database records following data:
book_isdn // unique identifier of each book. book_cat book_title book_author etc..
along this, have created table book categories stores following:
cat_id cat_title
i have defined following rows in categories table:
cat_id 1 = business books cat_id 2 = computing books cat_id 3 = science books cat_id 4 = history books etc
the problem:
in form allows staff member add new book, have list:
<select multiple name="b_category" style = "width:150px" required> <?php $get_cats = "select * categories"; $run_cats = mysqli_query($connect, $get_cats); while ($row_cats = mysqli_fetch_array($run_cats)) { $cat_id = $row_cats['cat_id']; $cat_title = $row_cats['cat_title']; echo "<option value='$cat_id'> $cat_title </option>"; } ?> </select>
i want add new book 'books' table corresponding cat_id category book belongs (i.e. business, computing etc.).
however, book can in 2 categories, i.e. book can both in field of business , computing.
the question:
how can alter form selects multiple options , adds them database, along cat_id?
for example:
if using form complete other fields , select computing , business list, want upon clicking "add new book", form data sent 'books' table able see new book , under field of book_cat, see 1,2.
i stumped. there way approach issue? hope have explained well.
thanks.
ok, let's start have not asked for.
a) db design
please not store concatenated id value 1,2
in book_cat
. makes lookups , search hard, because need fetch & split every single time. might work small systems.
what looking relation table books categories.
name books_to_categories
, book_id
, cat_id
.
query: select cat_id books_to_categories book_id = 2
;
result: array 1 or more ids, resolve cat_id
it's name (cat_title
) via category
table.
the keyword here database normalization.
b) formular
ok, have drop down list box, can multiple selections. now, values of these selections need transfered server side. 1 trick use array syntax, instead of
<select name="b_category" size=4 multiple>
just use
<select name="b_category[]" size=4 multiple>
and on server-side var_dump($_post['b_category']);
see values received. iterate on values of array , make database entries.
Comments
Post a Comment