在mysql数据库中插入更新和删除复选框数据

时间:2011-09-22 06:35:04

标签: php mysql

如何在mysql数据库表中插入更新和删除复选框数据。我需要mysql查询所有操作。我只有一个数据库表用于该操作。提前致谢

<input type="checkbox" name="sports" value="Cricket" /> Cricket 
<input type="checkbox" name="sports" value="Football" />Football 
<input type="checkbox" name="sports" value="Chess" />Chess 

数据库结构

ID ,NAME, AGE ,SPORTS(checkbox need to save)

2 个答案:

答案 0 :(得分:1)

你应该改变你的表架构,它甚至不是在1NF中,就像你拥有它一样。你应该创建至少两个表来处理这个问题,但我会建议三个表,考虑到体育将重复的事实。

这些将是你的表...

用户

id | name | age

<强>运动

id | sport

<强> user_sports

user_id | sport_id

这些是查询...

当您生成复选框时,您可以从sports表格中选择,作为值,您可以输入运动的ID,而不是名称。

插入注意插入,您将使用mysql_insert_id获取用户的ID,该ID将用于关系表。

INSERT INTO users(name, age) VALUES('John', 22);
INSERT INTO user_sports(user_id, sport_id) VALUES(mysql_insert_id(), 123);

选择如果您的复选框将包含运动的ID为值

    SELECT u.id user_id, u.name, u.age, s.sport
      FROM users u
INNER JOIN user_sports us
        ON u.id = us.user_id
       AND us.sport_id = 123
INNER JOIN sports s
        ON us.sport_id = s.id

选择,如果您有运动名称

    SELECT u.id user_id, u.name, u.age, s.sport
      FROM users u
INNER JOIN user_sports us
        ON u.id = us.user_id
INNER JOIN sports s
        ON us.sport_id = s.id
       AND s.sport = 'Football'

删除

    DELETE u, us 
      FROM users AS u
INNER JOIN user_sports AS us
        ON u.id = us.user_id
INNER JOIN sports AS s
        ON us.sport_id = s.id
       AND s.sport = 'Basketball'

答案 1 :(得分:0)

像Shef所说,你需要这3张表usersportuser_sport

用户

+----+----------------+-----+
| id | name           | age |
+----+----------------+-----+
|  1 | Freddy Mercury |  65 |
|  2 | Ian Gillan     |  66 |
|  . | .              |   . |
+----+----------------+-----+

<强>运动

+----+----------+
| id | sport    |
+----+----------+
|  1 | Cricket  |
|  2 | Football |
|  3 | Chess    |
+----+----------+

<强> user_sport

+---------+----------+
| user_id | sport_id |
+---------+----------+
|       . |        . |
+---------+----------+

使用此php生成复选框:

$sql = '/* Current User Sports */
SELECT
  sp.id AS "sport_id"
, sp.name As "sport"
, us.user_id AS "checked"
FROM sport AS sp
LEFT JOIN user_sport AS us ON (
  sp.id = us.sport_id
  AND user_id = '.$user_id.'
)
;';
$result = query($sql);
foreach ($result as $row) {
?>
  <label>
    <input type="checkbox" name="sports[<?php echo ($row['sport_id']) ?>]" checked="checked" />
    <?php echo ($row['sport']) ?>
  </label>
<?php
}

这会给你这个HTML:

<input type="checkbox" name="sports[1]" checked="checked" />Cricket 
<input type="checkbox" name="sports[2]" checked="checked" />Football 
<input type="checkbox" name="sports[3]" checked="checked" />Chess 

更新部分

首先查询(删除当前$ user_id的值):

DELETE FROM user_sport WHERE user_id = $user_id;

第二个查询(插入当前$ user_id的新值):

$sql = 'INSERT INTO user_sport
  (user_id, sport_id)
VALUES
  (';
$tmp = array();
foreach ($sports as $sport_id => $void) {
  $tmp[] = "($user_id, $sport_id)"
}
$sql .= implode("\n,   ", $tmp).'
  )
;';

这适用于插入/更新/删除