我花了很长时间试图弄清楚如何遍历我发布的表单数据并插入到 mysql。我的数据库表包含两列“名称”和“年龄”
我的表格:
<form action="form.php" method="post">
<input type="text" name="data[][name]" value=""/>
<input type="text" name="data[][age]" value=""/>
<input type="text" name="data[][name]" value=""/>
<input type="text" name="data[][age]" value=""/>
<input type="text" name="data[][name]" value=""/>
<input type="text" name="data[][age]" value=""/>
<input type="text" name="data[][name]" value=""/>
<input type="text" name="data[][age]" value=""/>
<input type="text" name="data[][name]" value=""/>
<input type="text" name="data[][age]" value=""/>
<input type="text" name="data[][name]" value=""/>
<input type="text" name="data[][age]" value=""/>
<input type="submit" value="submit" name="submit" />
</form>
PHP:
<?php
// Create Mysqli object
$db = new mysqli('localhost', 'root', 'root', 'database');
// Create statement object
$stmt = $db->stmt_init();
if (isset($_POST['submit'])) {
// Create a prepared statement
if($stmt->prepare("INSERT INTO contact (name, age) VALUES (?, ?)")) {
// Bind your variables to replace the ?s
$stmt->bind_param('si', $name, $age);
$returnedData = $_POST['data'];
foreach($returnedData as $data) {
$name = $data['name'];
$age = $data['age'];
$stmt->execute();
}
// Close statement object
$stmt->close();
}
}
// Close Connection
mysqli_close($link);
?>