使用php向数据库添加multiselect

sdnqo3pr  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(291)

我正试图从一个多选数据库中获取一个输入。下面是我使用的表单中select字段的一个片段。我确实找到了[]的建议,所以我加了这个。是向前迈出的一大步

<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>

下面是我从文章中读取信息的方法如果我只回显foreach()行(从stackoverflow上的另一篇文章中获取),效果很好,但是我想将它添加到数据库中,我不知道如何完成。我真的需要一些帮助。

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

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

$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);
nnsrf1az

nnsrf1az1#

如果它们是数据库中的单个记录,则需要使用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上阅读有关mysqli的更多信息http://php.net/manual/en/book.mysqli.php 以及post/loopshttp://php.net/manual/en/control-structures.foreach.php 以及http://php.net/manual/en/reserved.variables.post.php

相关问题