如何使用MySQL和MySQL

时间:2019-01-08 11:13:40

标签: php mysqli

我有一个包含多个选择列表的表单。表单中有多个选择列表(块)。如何将多个选择数据提交到数据库?

我试图创建一个foreach语句,但问题是它仅在数据库中提交一个选项。

    <?php 
$db = mysqli_connect('localhost','root','','trial') or die($db);
if (isset($_POST['submit'])) {
$marks = mysqli_real_escape_string($db,$_POST['marks']);
$subjects= $_POST['subject'];
$farming= $_POST['farming'];
foreach ($subjects as $i) {
    $subject = $i;
    $sql = "INSERT INTO `trial_table` (`subjects`, `marks`) VALUES ('".mysqli_real_escape_string($db,$subject)."', '$marks')";
mysqli_query($db,$sql);
}
$sql1 = "INSERT INTO `trial_table` (`marks`) VALUES ('$marks')";
mysqli_query($db,$sql1);
}
 ?>
<body>
    <form method="POST" action="test.php">
    <select id="multiselect" name="farming[]" multiple="multiple" required>
    <option value="Irrigation">Irrigation</option>
    <option value="Fertilizer">Fertilizer</option>
    <option value="Pesticide">Pesticide</option>    
    </select>
    <select id="multiselect" name="subject[]" multiple="multiple" required>
    <option value="Irrigation">Technology</option>
    <option value="Fertilizer">Science</option>   
     </select>
    <div class="input-group">
        <label>Marks</label>
        <input type="number" name="marks">      
    </div>  
    <button type="submit" name="submit" class="btn">SUBMIT</button> 
      </form>
</body>
</html>`enter code here`

我希望表单将选定的数据不仅仅是一个提交到数据库。

2 个答案:

答案 0 :(得分:0)

如果要在单行中插入数据

$subject = implode(',', $subjects);

这将返回您在每个主题之间带有分隔符','的单个字符串。 现在,您可以将整个内容插入到单个列中。

然后使用带有','的explode函数将其检索:它将为您提供相同的数组$ subjects;

答案 1 :(得分:0)

我已将其简化到此级别,但是唯一的问题是我在数据库中没有数据。可能是什么问题/

if <?php 
$db = mysqli_connect('localhost','root','','trial') or die($db);
if (isset($_POST['submit'])) {
$marks = mysqli_real_escape_string($db,$_POST['marks']);
$subjects= $_POST['subject'];
$others= $_POST['others'];

foreach ($others as $t){

    $sql1 = "INSERT INTO `trial_table` (`others`) VALUES ('".mysqli_real_escape_string($db,$t)."')";
mysqli_query($db,$sql1);
}

foreach ($subjects as $i){

    $sql = "INSERT INTO `trial_table` (`subjects`, marks) VALUES ('".mysqli_real_escape_string($db,$i)."' , '$marks')";
mysqli_query($db,$sql);
}


}
 ?>
<body>
    <form method="POST" action="test.php">

    <select id="multiselect" name="subject[]" multiple="multiple">
    <option value="Irrigation">Technology</option>
    <option value="Fertilizer">Science</option>   
     </select>
     <select id="multiselect" name="others[]" multiple="multiple">
    <option value="Ball">Sports</option>
    <option value="Netball">Gymics</option>   
     </select>
    <div class="input-group">
        <label>Marks</label>
        <input type="number" name="marks">      
    </div>  
    <button type="submit" name="submit" class="btn">SUBMIT</button> 
      </form>
</body>
</html>