PHP MySQL的:从数组中插入数据 [英] PHP mysql: inserting data from an array
问题描述
我无法提取阵列插入到数据库中。我的形式接受输入多元,动态号码,以便我在一个阵列中的数据具有输入phonenos []和phonetypes []:
I'm having trouble extracting arrays to insert into the database. My form accepts multiple and dynamic number of inputs so I have the data in an array with inputs phonenos[] and 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
));
所以,我做了一个的var_dump
的变量$ PHONENO和$ PHONETYPE一个提交多个电话号码后,它只能打印出来最后的数量和类型,而我想要的全部所提交列表。如何获得的所有数据,所以我可以将其插入到数据库?
So I did a var_dump
on variables $phoneno and $phonetype after a submission of multiple phone numbers and it only printed out the last number and type whereas I wanted the entire list that was submitted. How do I get all the data so I can insert it into the database?
推荐答案
我想通了,通过一个for循环的解决方案。
I figured out the solution through a for loop.
$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
));
}
这篇关于PHP MySQL的:从数组中插入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!