doukao5073 2014-05-15 04:49
浏览 33
已采纳

PHP保存到数据库时的变量变量

I have a save.php page that is being called using Ajax, it contains the following elements:

$q1 = $_POST["q1"];
$q2 = $_POST["q2"];
$q3 = $_POST["q3"];
$q4 = $_POST["q4"];
$q5 = $_POST["q5"];

$proc = mysqli_prepare($link, "INSERT INTO tresults 
(respondent_id, ip, browser, company, q1, q2, q3, q4, q5) 
VALUES (?, ?, ?, ?, ?, ?, ?, ?);");

mysqli_stmt_bind_param($proc, "issiiiii", 
$respondent_id, $ip, $browser, $company, 
$q1, $q2, $q3, $q4, $q5);

At the moment, the save.php page is manually coded but I am sure there must be a way of using variable variables to automate this page to a degree, especially when the number of fields exceeds 100 that I am saving to the database.

I am, however, having trouble getting my head around using variable variables and could use some guidance.

I am have, to no avail, tried the following:

for ($i = 1; $i <= 5; $i++) {
    echo '$q.$i = $_POST["q".$i];';
}

and also

for ($i = 1; $i <= 5; $i++) {
   $q.$i = $_POST["q".$i];
}

Any and all advice welcomed.

Thanks.

  • 写回答

2条回答 默认 最新

  • douchuza8908 2014-05-15 04:54
    关注

    You can use:

    ${'q'.$i} = $_POST['q'.$i];
    

    Also:

    for ($i = 1; $i <= 5; $i++) {
        echo '$q.$i = $_POST["q".$i];';
    }
    

    should be:

    for ($i = 1; $i <= 5; $i++) {
        echo "$q.$i = $_POST['q'.$i];";
        //   ^                       ^
    }
    

    otherwise variables won't be interpolated within the string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题