简体   繁体   中英

Updating SQL with multiple categories and checkbox (PHP)

I have table of category like this

Table Name : personality

 id | Category
  1 | cute
  2 | rich
  3 | stupid
  4 | funny
  5 | famous

All i want to do is make to check box option with php for this personality table and update other table with multiple category

and my form:

  <form>
    Name : <input name="user" type="text" id="user" value="<?php echo $line['user'];?>" />
    Personality : <?php $personality=mysql_query("select * from personality");
                  while($data=mysql_fetch_array($personality)){
                  $check = ($line['usr_char']==$data['category'])?"checked" : "";
                  <label for='$data[kategori]'>
                  <input type='checkbox' id='usr_char' checked value='$data[category]'>
                  <span class='custom checkbox $check'></span> $data[category]</label><br>}?>

How do I post the category of personality table into other table with multiple category?

Here is example for the result : Table Name : people

  name | usr_char
  abby | cute,rich,funny
  andy | famous,funny

Create another table called people_personality , with the following:

  • id <-- your primary key
  • person_id <-- your primary key from your "People" table
  • personality_id <-- your primary key from your "Personality" table

Suppose you have in your People table:

id - name
1  - abby
2  - andy

Now you want to assign abby cute , rich , and funny :

INSERT INTO people_personality VALUES ('',1,1),('',1,2),('',1,3)

For one you are missing a name on the input element.

<input type='checkbox' id='usr_char' name='attribute[]' checked value='$data[category]'>

After that on the to get the value to update your people table with you would just use

$attributes = implode(",", $_POST["attribute"]);

My suggestion is don't try to store multiple comma separated values in an SQL field . It has many disadvantages including,

  • Retrieving the individual values is a tedious process
  • It is not readable
  • Becomes difficult to maintain

So, instead use a many-to-many link table. For example, you can have tables this way:

Table 1:

Id | Category

 1 | cute
 2 | rich
 3 | stupid
 4 | funny
 5 | famous

Table 2:

Name | Usr_char

abby | cute
abby | rich
abby | funny
andy | famous
andy | funny

Having this way makes it easier for example, to add characters later and remove them and even to select them.

To retrieve:

SELECT * FROM table_name WHERE Name = 'abby';

To add:

INSERT INTO table_name (Name, Usr_char) VALUES ('abby', 'cute');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM