使用php将multiselect添加到数据库

时间:2018-08-14 18:22:55

标签: php mysql

我正在尝试将多选输入输入数据库。以下是我具有的表单中的选择字段的摘要。我确实找到了[]的建议,因此我添加了该建议。是向前迈出的一大步

<select name="project_dicipline[]" data-placeholder="Select uw dicipline(s)" class="chosen-select" multiple style="width:350px;">
     <option value=""></option> 
     <option value="Elektra_LS">Elektra LS</option> 
     <option value="Elektra_MS">Elektra MS</option> 
     <option value="Elektra_OV">Elektra OV</option>
</select>

下面是我从_POST中读取信息的信息,如果我只回显foreach()行(从stackoverflow上的另一篇文章中得到它),它就可以正常工作,但是我想将其添加到数据库中,并且我不确定该怎么做。我真的可以为此提供一些帮助。

$project_dicipline = array();
foreach ($_POST['project_dicipline'] as $project_dicipline)
   $project_dicipline = mysqli_real_escape_string($conn, $project_dicipline);
   echo $project_dicipline;

-编辑- 下面是与数据库的连接。我知道的那部分有效,因为表单的其余部分都经过验证并添加到表单中。因此,我从查询中删除了很多字段。 (在运行查询之前,所有变量都已转义)

    $conn = mysqli_connect($servername, $usernamedb, $passwordDB, $database);
    if (!$conn) 
    {
        die("Connection failed: " . mysqli_connect_error());
    }


    $query = "INSERT INTO projects (project_status, project_name, project_client, project_diciplines)

     VALUES('New', '$project_naam', '$project_plaats', '$project_client_company', '$project_dicipline')";
     mysqli_query($conn, $query);

1 个答案:

答案 0 :(得分:0)

如果要将它们作为数据库中的单个记录,则需要使用foreach循环将其插入

$conn = mysqli_connect($servername, $usernamedb, $passwordDB, $database);
if (!$conn) 
{
    die("Connection failed: " . mysqli_connect_error());
}

if ($stmt = mysqli_prepare($conn, "INSERT INTO projects (project_status, project_name, project_client, project_diciplines) VALUES('New', ?, ?, ?, ?)")) {

    $project_dicipline = array();
    foreach ($_POST['project_dicipline'] as $project_dicipline){
         $project_dicipline = mysqli_real_escape_string($conn, $project_dicipline);

         mysqli_stmt_bind_param($stmt, $project_naam, $project_plaats,$project_client_company,$project_dicipline);

         /* execute query */
         mysqli_stmt_execute($stmt);
    }

}

您可以在php.net http://php.net/manual/en/book.mysqli.php上阅读有关mysqli的更多信息,以及http://php.net/manual/en/control-structures.foreach.phphttp://php.net/manual/en/reserved.variables.post.php的发布/循环