【发布时间】:2014-07-21 15:55:58
【问题描述】:
我正在尝试将此数组正确添加到数据库中。我有 3 个输入框,当我回显 $key 时,我的所有信息都在那里,就像 Jonesbass23 一样,但是当我运行代码时,每个字段都会在数据库中获得一个新行,它不会全部进入 1 行,并且值会进入错误列也是如此。还将根据用户想要的输入字段数量动态添加我的 $_POST 数组,因此我的数据库条目可以是多个。以为我掌握了它,但猜不到。任何帮助将不胜感激,谢谢。
<?php
session_start();
$errmsg_arr = array();
$errflag = false;
require_once 'dbconfig.php'; // Database Connection
//Retrieve data input from addfish.php
$username = $_SESSION['username'];
print_r($_POST);
}
//Returns error message text on screen
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: addfish.php");
exit();
}
//Insert data into database
$statement = $dbc->prepare("INSERT INTO entries(username, species, length, weight)
VALUES(:username, :species, :length, :weight)");
foreach($_POST as $key => $data) {
echo $key;
echo $data['species']; // The data of species1, species2, or species3, etc.
echo $data['length'];
echo $data['weight'];
try {
$statement->execute(array(
"username" => "$username",
"species" => $data['species'],
"length" => $data['length'],
"weight" => $data['weight']
));
}
catch(PDOException $e) {
echo "Exception caught: $e";
}
}
?>
【问题讨论】: