从$_POST字段动态创建表单上的变量


Dynamically create variables from $_POST fields on a form

我有麻烦从$_POST变量动态创建变量。

在一个表单上,我有一个表格,人们在那里填写司机信息。表最初只有一行,但如果需要添加更多行,则用户按下按钮,添加新行,并且新行中的字段名增加,即:driver1, driver2, driver3, driver4。

我想让这个匹配我的PHP脚本:

$count=1; 
while($count<=100) {
  $driver . string($count) = $_POST['driver . string($count)'];
  $count++;
} 

通常我会为每个$_POST变量创建一个新变量,但在有多达100行的情况下,我想用循环来处理这个问题。

我收到的错误是:

Fatal error: Can't use function return value in write context in C:'Inetpub'vhosts'host'httpdocs'process.php on line 11

不建议以编程方式生成变量。然而,这是可能的:

${'driver'.$count}:

$count=1; 
while($count<=100) {
  ${'driver'.$count} = $_POST['driver' . $count];
  $count++;
} 

更多关于动态变量的信息在这里。


我将使用数组来完成这个任务:

$driver[$count]=$_POST['driver'.$count];

然后你可以做

foreach ($driver as $count => $postValue){
    // $handling here
}
// OR to access a specific driver
$driver[$count];

试试这个

<?php
$count=1; 
while($count<=100) {
  ${'driver' . $count} = $_POST['driver' . $count];
  $count++;
}
?>

由于$count是一个数值,所以不需要进行字符串强制转换。

我认为这可以帮助你改进你的代码计数特定输入的次数出现在一个表单

您可以使用extract将每个$_POST键映射到同名的变量。

extract($_POST,EXTR_OVERWRITE,'prefix');

这将导致变量命名为$prefix_driver1, $prefix_driver2…等等。

(前缀的使用是可选的,但如果不使用,恶意用户可以通过更改表单的输入名称来操纵您的脚本变量)