我的页面中有多个组合框,这是代码:
<select name="usulan[]" size="3" multiple>
<option name="satu" value="satu"> satu </option>
<option name="dua" value="dua"> dua </option>
<option name="tiga" value="tiga"> tiga </option>
<option name="empat" value="empat"> empat </option>
</select>
然后我检查了多个这样的选项:
我希望我检查的每个选项都插入到我的数据库中的一个字段(field_usulan)。
所以,如果我有这样的表:
id | alat | field_usulan
-----------------------------
1 | |
插入后,我希望它变成这样的东西:
id | alat | field_usulan
-----------------------------
1 | RJ45 | satu, dua
如果我使用此代码:
<?php
if(isset($_REQUEST['submit'])) {
include "../conf/koneksi.php";
$count = count($_POST['alat']);
for($i = 0; $i < $count; $i++){
if(!empty($_POST['alat'][$i]))
{
$alat = mysql_real_escape_string($_POST['alat'][$i]);
$usulan = mysql_real_escape_string($_POST['usulan'][$i]);
$sql= "ALTER TABLE tb_inventaris AUTO_INCREMENT = 1";
mysql_query($sql);
$sql2=mysql_query("INSERT INTO tb_inventaris (alat,usulan)
VALUES
('$alat', '$usulan')") or die(mysql_error());
echo "<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"0; URL='../koordinator.php?url=index'\">";
}else{
echo "<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"0; URL='../koordinator.php?url=index'\">";
}
}
}
?>
它只会插入第一个选项,如下所示:
id | alat | field_usulan
-----------------------------
1 | RJ45 | satu
抱歉我的语言不好。
答案 0 :(得分:1)
插入时,使用PHP的implode()函数。
$usulan = isset($_POST['usulan']) ? implode(',', $_POST['usulan']) : '';
$sql2=mysql_query("INSERT INTO tb_inventaris (alat,usulan)
VALUES
('$alat', '$usulan')") or die(mysql_error());
希望它适合你。
答案 1 :(得分:1)
通过迭代遍历所选值
添加所有以逗号分隔的值$query = "INSERT INTO tb_inventaris (alat,usulan) VALUES ";
$values = array();
foreach ($_GET['usulan'] as $selectedOption){
$values[] = $selectedOption;
}
$query .= "('$alat', '".implode(',',$values)."')";
答案 2 :(得分:0)
使用json_encode的数据库中的数组
CREATE TABLE `tb_inventaris` (
`id` int(11) NOT NULL,
`alat` varchar(20) NOT NULL,
`usulan` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<input type="text" name="alat">
<select name="usulan[]" size="3" multiple>
<option name="satu" value="satu"> satu </option>
<option name="dua" value="dua"> dua </option>
<option name="tiga" value="tiga"> tiga </option>
<option name="empat" value="empat"> empat </option>
</select>
<?php
if (isset($_REQUEST['submit'])) {
include "../conf/koneksi.php";
$alat = $_POST['alat'];
// if "$_POST['usulan']" is exist,
// convert it into string using json_encode,
// otherwise set string blank ("")
$usulan = ( ! empty($_POST['usulan'])) ? json_encode($_POST['usulan']) : "";
/* Create post */
$sql = "INSERT INTO tb_inventaris ";
$sql .= "( ";
$sql .= "alat, ";
$sql .= "usulan ";
$sql .= ") ";
$sql .= "VALUES ";
$sql .= "( ";
$sql .= "'$alat', ";
$sql .= "'$usulan' ";
$sql .= ")";
mysql_query(sql);
}
?>
显示“ index.php ”
<?php
// check it if not blank,
// use json_decode and implode functions
$favorite = ( ! empty(json_decode($row['usulan']))) ? implode(", ", json_decode($row['usulan'])) : "";
echo $usulan;
?>