我无法提取数组以插入数据库。我的表单接受多个动态数量的输入,所以我将数据放在一个数组中,输入phonenos []和phonetypes []:
<form name="add" action="" method="POST">
<input name="name" type="text" placeholder="Name"></input><br />
<input name="qty" type="text" placeholder="Qty"></input><br /> -->
<input class="form-control required" name="phonenos[]" maxlength="14" type="text" placeholder="number..."><br>
<select class="form-control" name="phonetypes[]">
<option value="0">Choose a phone type</option>
<option value="Main">Main</option>
<option value="Fax">Fax</option>
<option value="Mobile/Direct">Mobile/Direct</option>
</select>
<div id="addmore">
<input type="button" value="Add More" onClick="addRow(this.form)"></input>
</div>
<input type="submit" value="submit" name="action"></input>
</form>
在我的PDO查询中:
..... first query insertion...
$phonenos = $_POST['phonenos'];
foreach($_POST['phonenos'] as $phoneno) {
$phoneno;
}
$phonetypes = $_POST['phonetypes'];
foreach($_POST['phonetypes'] as $phonetype) {
$phonetype;
}
$sql = 'INSERT INTO phone (p_id, phoneno, phonetype) values (:p_id, :phoneno, :phonetype)';
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phoneno'=>$phoneno,
':phonetype'=>$phonetype
));
所以我在提交多个电话号码后对变量$ phoneno和$ phonetype做了var_dump
,它只打印出最后一个数字和类型,而我想要提交的整个列表。如何获取所有数据,以便将其插入数据库?
答案 0 :(得分:0)
如果你想在同一列中插入所有数字,那么我认为最好的解决方案是在插入db之前序列化它们。
$phonenos = serialize($_POST['phonenos']);
$phonetypes = serialize($_POST['phonetypes']);
$sql = 'INSERT INTO phone (p_id, phoneno, phonetype) values (:p_id, :phoneno, :phonetype)';
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phoneno'=>$phonenos,
':phonetype'=>$phonetypes
));
答案 1 :(得分:0)
我通过for循环找到了解决方案。
$phones = $_POST['phones'];
$phonetypes = $_POST['phonetypes'];
for($i = 0, $j = 0; $i <= $phones, $j <= $phonetypes; $i++, $j++) {
$phone = $phones[$i];
$phonetype = $phonetypes[$j];
$sql = "INSERT INTO phone (p_id, phone, phonetype) values (:p_id, :phone, :phonetype)";
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phone'=>$phone,
':phonetype'=>$phonetype
));
}