我将一些输入字段附加到我的容器中,并希望为我的mysql数据库中的每个条目添加。到目前为止,这种方法运作良好:
<?php
if (isset($_POST['submit_val'])) {
if ($_POST['name']) {
foreach ( $_POST['name'] as $key=>$value ) {
$pdo = $db->prepare('INSERT INTO friends (name) values(:name) ');
$pdo->execute(array(
':name' => $value,
));
}
}
echo "<i><h2><strong>" . count($_POST['name']) . "</strong> items added</h2></i>";
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
<form method="post" action="">
<div id="container">
<p id="add_field"><a href="#"><span>Click To Add</span></a></p>
</div>
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<script type="text/javascript">
var counter = 0;
$(function() {
$('p#add_field').click(function() {
counter += 1;
$('#container').append(
'<strong>No. ' + counter + '</strong><br />' + '<input id="field_' + counter + '" name="name[]' + '" type="text" /><br/>');
});
});
</script>
但我希望不仅name
,age
和gender
字段为字段:
$('#container').append('<strong>No. ' + counter + '</strong><br />' + '<input id="field_' + counter + '" name="name[]' + '" type="text" /><input id="field_' + counter + '" name="age[]' + '" type="text" /><input id="field_' + counter + '" name="gender[]' + '" type="text" /><br/>');
并将它们添加到数据库中:
$pdo = $db->prepare('INSERT INTO friends (name,age,gender) values(:name,:age,:gender) ');
$pdo->execute(array(
':name' => $value,
':age' => $value,
':gender' => $value,
));
但现在我有一个理解的逻辑问题。如何将其他值放入我的foreach循环foreach ( $_POST['name'] as $key=>$value ) {
中,因为我需要一个循环来处理所有值?
我可以想象这样的事情:
foreach ( $_POST['name'] as $key=>$name && $_POST['age'] as $key=>$age && $_POST['gender'] as $key=>$gender ) {
答案 0 :(得分:1)
假设所有三个字段的出现都相同,您可以使用:
foreach($_POST['name'] as $key=>$val){
echo $val." ".$_POST['age'][$key]." ".$_POST['gender'][$key]."<br>";// you can use these value in your insert
}