将复选框数据从php存储到数据库

时间:2019-04-30 18:00:21

标签: php database checkbox

我的数据库中有以下表格:

CREATE TABLE subjects (
  subject_id int(11) NOT NULL AUTO_INCREMENT,
  subject text,
  PRIMARY KEY (subject_id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

CREATE TABLE users (
  id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  username varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE users_subjects (
  users_subjects_id int(11) NOT NULL AUTO_INCREMENT,
  user_id_fk int(11),
  subject_id_fk int(11),
  FOREIGN KEY(user_id_fk) REFERENCES users(id),
  FOREIGN KEY(subject_id_fk) REFERENCES subjects(subject_id),
  PRIMARY KEY (users_subjects_id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;

在“ users_subjects”表中,我试图将“ subjects”和“ users”表关联起来。 表中的所有数据都是从我的index.php输入的。

我从index.php中引入subject_name,每次输入一个新的主题时,都会在添加用户的部分中创建如下所示的复选框:

enter image description here

这是输入用户的代码,每次引入主题时都会在其中形成复选框(index.php):

<form method="post" action="register.php">
    <?php include('errors.php'); ?>
    <div class="input-group">
        <label>User</label>
        <input type="text" name="username" value="">
    </div>
    <div class="input-group">
        <label>Subjects</label>
    </div>
    <div>
        <?php
        $sql = "SELECT subject FROM subjects"; /*Select from table name: subjects*/
        $result = $conn->query($sql); /*Check connection*/
        if($result)
        {
            foreach($result as $row)
            {
                echo "<input type='checkbox' name='subject' value='" . htmlspecialchars($row['subject']) . "' /> <label>" . $row['subject'] . " </label><br>";
            }
        }
        ?>
    </div>

    <div class="input-group">
        <button type="submit" class="btn" name="reg_user">Add new user</button>
    </div>
</form>

我设法在“用户”表中输入用户名。

我遇到的问题是,我不知道如何支持“ users_subjects”表中的复选框数据。我被困住了,无法解决。有人可以帮我吗?

这是我为“ register.php”编写的代码:

<?php
$username = "";
$subject = "";
$errors = array();

include('Conexion.php');

if (isset($_POST['reg_user'])) {
    // receive all input values from the form
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $subject = mysqli_real_escape_string($conn, $_POST['subject']);


    if (empty($username)) { array_push($errors, "Username is required"); }
    if (empty($subject)) { array_push($errors, "Subject is required"); }

    $user_check_query = "SELECT * FROM users WHERE username='$username' LIMIT 1";
    $result = mysqli_query($conn, $user_check_query);
    $user = mysqli_fetch_assoc($result);

    if ($user) { // if user exists
        if ($user['username'] === $username) {
            array_push($errors, "Username already exists");
        }
    }
    // Register user if there are no errors in the form
    if (count($errors) == 0) {
        $query = "INSERT INTO users (username) 
           VALUES('$username')";
        mysqli_query($conn, $query);


        $insert_id = mysqli_insert_id($conn);
        $subject=implode(',',$_POST['subject']);
        //Count subjects and checks if the subject exists
        for($i=0; $i<count($subject); $i++) {

            $query = "SELECT subject_id FROM subject where subject='$subject[$i]'";
            $result = $conn->query($query); /*Check connection*/

            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $subject_id = $row["subject_id"];
                $query = "INSERT INTO users_subjects (user_id_fk, subject_id_fk)
           VALUES('$insert_id', '$subject_id')";
                mysqli_query($conn, $query);
            } else {
                /*???*/
            }
        }



        header('location: indexAdmin.php');
    }
}
?>

2 个答案:

答案 0 :(得分:2)

您的主要问题就在这里:

        foreach($result as $row)
        {
            echo "<input type='checkbox' name='subject' value='" . htmlspecialchars($row['subject']) . "' /> <label>" . $row['subject'] . " </label><br>";
        }

使用相同名称的复选框时,需要将其视为数组。看这个:

        foreach($result as $row)
        {
            echo "<input type='checkbox' name='subject[]' value='" . htmlspecialchars($row['subject']) . "' /> <label>" . $row['subject'] . " </label><br>";
        }

通过将“ name =”更改为“ subject []”,php会将选定的值存储到数组中:

        $subject = $_POST['subject'];

这时,$ subject将是一个包含每个单击框的值的数组。 (请不要忘记进行适当的尽职调查并验证这些数据。这超出了您的问题范围,但是我确实想提及它。)

如果只想将数组存储在数据库中,则需要“ serialize()”数组。这将使用您的数组变量,并将其转换为代表数组的字符串。然后,您可以将该字符串存储到数据库中,并且在读取数据库时,可以将字符串“ unserialize()”“放回”数组中。您也可以只使用数组并使用implode制成逗号分隔的列表。

例如:

将数组变成字符串:

$str = serialize($subject);

要将序列化的字符串转换回数组:

$arrSubject = unserialize($str);

或者将数组放入逗号分隔的字符串中以这种方式存储:

$str = implode(", ", $subject);

以及一些链接:

https://www.php.net/manual/en/function.serialize.php

https://php.net/manual/en/function.implode.php

玩得开心:)

答案 1 :(得分:0)

正如您所说:我的问题是我不知道如何在“ users_subjects”表中支持复选框数据,您可以创建另一个文本类型字段并将值保留为JSON格式,其中复选框的类型,值是true还是false取决于复选框是否标记。 es。 {sat:true,ICT:false,subject:false}