I'm having a heck of a time trying to figure out how to loop through my posted form data and inserting to mysql. My database table contains two columns "name" and "age"
My form:
<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);
?>
param s = &$name
internally, establishing a reference to the specified variable. change the variable's value, and next time you exec() the prepared statement, it gets that changed value. – Marc B Jul 9 at 17:09print_r($returnedData)
orprint_r($_POST)
. Your array structure/data is not what you think it is. – Sean Jul 9 at 17:10var_dump($stmt->execute)
. all of your db operations are simply assuming success. – Marc B Jul 9 at 17:12