【发布时间】:2019-04-01 15:13:23
【问题描述】:
我正在使用 foreach 生成几个动态输入。每个输入通过循环遍历文本文件中的数组获得其name 和id。
然后将表单数据发送到另一个 PHP 页面以使用 POST 执行一些数据库查询。
我面临的问题是每个输入值都返回NULL。
我不知道发生了什么,因为当我在网络选项卡上查看 Web 控制台时,我可以看到正在收集参数。
array.txt
first_name
last_name
occupation
company_name
industry
city
country
countryCode
phone
email
address
stateProvince
postalZipeCode
form.php
//get array of names and ids for inputs
$array = explode("\n", file_get_contents('array.txt'));
//loop through the array
echo '<form method="POST" action="insert.php">';
foreach($array as $input) {
echo '<label>'.$input.'</label>'
. '<input type="text" id="'.$input.'" name="'.$input.'" required="required" class="form-control" placeholder="'.$input.'">';
echo '<br>';
}
echo '<input type="submit" value="Submit">';
echo '</form>';
网络标签(网络控制台)
插入.php
if (!empty($_POST)) {
//get variables
if (isset($_POST['first_name'])) {
$first_name= $_POST['first_name']; //1.
}
if (isset($_POST['last_name'])){
$last_name=$_POST['last_name']; //2.
}
if (isset($_POST['occupation'])) {
$occupation=$_POST['occupation']; //3.
}
if (isset($_POST['company_name'])) {
$company_name=$_POST['company_name']; //4
}
if (isset($_POST['industry'])){
$industry = $_POST['industry']; //5
}
if (isset($_POST['city'])) {
$city = $_POST['city']; //6
}
if(isset($_POST['country'])){
$country=$_POST['country']; //7
}
if (isset($_POST['countryCode'])) {
$countryCode = $_POST['countryCode']; //8
}
if (isset($_POST['phone'])) {
$phone = $_POST['phone']; //9
}
if (isset($_POST['email'])) {
$email = $_POST['email']; //10
}
if (isset($_POST['address'])) {
$address = $_POST['address']; //11
}
if (isset($_POST['stateProvince'])) {
$stateProvince = $_POST['stateProvince']; //12
}
if (isset($_POST['postalZipeCode'])) {
$postalZipeCode = $_POST['postalZipeCode']; //13
}
// insert into table
$insertProspectQuery = $conn->prepare("INSERT INTO users (first_name, last_name, occupation, company,industry,city,country,countryCode,phone,email,address,stateProvince,postalZipeCode) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");
$insertProspectQuery->bind_param('sssssssssssss',$first_name,$last_name,$occupation,$company_name,$industry,$city,$country,$countryCode,$phone,$email,$address,$stateProvince,$postalZipeCode);
$insertProspectQuery->execute();
$insertProspectQuery->close();
$ok = 1;
} else {
//handle error
}
【问题讨论】:
-
如果你在
insert.php的顶部使用echo '<pre>'; var_dump($_POST): die();会告诉你什么? -
“我面临的问题是每个输入值都返回 NULL” — 你怎么知道?您的 PHP 将值分配给变量,然后不再使用它。
-
echo '<label>'.$input.'</label>'— 标签是无用的,除非您在其中放置表单控件或为其赋予for属性。 -
@Quentin :我在数据库中插入。并且所有行都返回 NULL。意思是,NULL 值被插入到表中。
-
那么插入可能有问题。您需要提供minimal reproducible example。