我有一个包含五个输入字段的html表单,可以输入一个或多个产品特征。输入的值应发送到SQL表。当所有5个字段都包含值时,这适用于for循环。
<input name="productmaingroupsinput[1]" size="80"/><br>
<input name="productmaingroupsinput[2]" size="80"/><br>
<input name="productmaingroupsinput[3]" size="80"/>
<input name="productmaingroupsinput[4]" size="80"/>
<input name="productmaingroupsinput[5]" size="80"/>
$productmaingroupsinput = $_POST["productmaingroupsinput "];
for ($i=1; $i<6; $i++) {
$sql="INSERT INTO productmaingroup (productmaingroup_id, product_id,
productmaingroups) VALUES ('', (SELECT master_id from producttable
WHERE productname='$ productname '), '".productmaingroupsinput
[$i]."')";
mysqli_query($db, $sql);
}
但是,当较少的字段填入条目时,我的SQL表中会出现空条目。现在,我想避免SQL表中的空字段。我用
试了一下 if (isset($_POST["productmaingroupsinput[$k]"])) {
$j = $k + 1;
}
或
$j = count($productmaingroupsinput);
for ($i=1; $i<$j; $i++) {
$sql="INSERT INTO productmaingroup (productmaingroup_id, product_id,
productmaingroups) VALUES ('', (SELECT master_id from producttable
WHERE productname='$ productname '), '".productmaingroupsinput
[$i]."')";
但它不起作用。
如何使for-loop动态化以便仅将输入的值发送到SQL表?
谢谢!
答案 0 :(得分:0)
你应该检查一下,如果value是null或者..如果($ _ POST [&#34; productmaingroupsinput&#34;] [$ i]!= NULL)那么只执行那个查询..我希望这会工作对你而言。
答案 1 :(得分:0)
你必须循环productmaingroupsinput post值并检查是否为空.do喜欢这样
public
答案 2 :(得分:0)
这是我的解决方案:
$master = mysqli_query($db, "SELECT master_id from producttable WHERE productname='{$productname}'");
$master_id = $master ? mysqli_fetch_field($master) : 'NULL';
foreach($_POST['productmaingroupsinput'] as $group) {
if($group=='') {
continue;
}
$groups[] = "('', {$master_id}, '".mysqli_real_escape_string($group)."')";
}
$result = mysqli_query($db, "INSERT INTO productmaingroup (productmaingroup_id, product_id, productmaingroups) VALUES ".implode(', ', $groups));