我想使用PDO预处理语句使用单个查询插入多行但我不想插入任何空白行。
实际上,我的表单中有四行你可以在下面的HTML中看到,当我只填充一行时,它也会插入三个空白行,但我不会插入任何空白行
Array
(
[Women] => Array
(
[S] => Array
(
[warehouse] => 22
[price] => 21212
)
)
[Men] => Array
(
[S] => Array
(
[warehouse] => 22
)
)
)
我的代码就像这样
<form method="post">
<table>
<tr>
<td><input type="text" name="col1"></td>
<td><input type="text" name="col2"></td>
</tr>
<tr>
<td><input type="text" name="col1"></td>
<td><input type="text" name="col2"></td>
</tr>
<tr>
<td><input type="text" name="col1"></td>
<td><input type="text" name="col2"></td>
</tr>
<tr>
<td><input type="text" name="col1"></td>
<td><input type="text" name="col2"></td>
</tr>
</table>
</form>
请帮助我......
答案 0 :(得分:0)
由于col1和col2是多个,因此您应该使用数组:必须更改数据库凭据并更改表名。测试目的我使用表名
test
。
<强>的index.php 强>
<?php
if(isset($_POST['submit'])){
$dbhost = "localhost"; //Set your hostname
$dbname = "dbname"; //set your dbname
$dbusername = "root"; //set your db username
$dbpassword = ""; //set your db password
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbusername,$dbpassword);
for ($i=0; $i <count($_POST['col1']) ; $i++) {
$rowNum = $i+1;
if($_POST['col1'][$i]!='' && $_POST['col2'][$i]!=''){
$statement = $link->prepare("INSERT INTO test(col1, col2) VALUES(:col1, :col2)");
$res = $statement->execute(array(
"col1" => $_POST['col1'][$i],
"col2" => $_POST['col2'][$i],
));
if($res)
echo "Row no: $rowNum Successfully inserted.<br>";
else
echo "Row no: $rowNum Failed to insert.<br>";
}else
echo "Row no: $rowNum single or double field empty.<br>";
}
}
?>
<form method="post">
<table>
<tr>
<td><input type="text" name="col1[]"></td>
<td><input type="text" name="col2[]"></td>
</tr>
<tr>
<td><input type="text" name="col1[]"></td>
<td><input type="text" name="col2[]"></td>
</tr>
<tr>
<td><input type="text" name="col1[]"></td>
<td><input type="text" name="col2[]"></td>
</tr>
<tr>
<td><input type="text" name="col1[]"></td>
<td><input type="text" name="col2[]"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>