【问题标题】:PHP Variable printing multiple variablesPHP变量打印多个变量
【发布时间】:2015-03-26 11:06:29
【问题描述】:

我有几个变量,例如:

$q1
$q2
$q3
...
$q50

我想将它们信息结合到一个变量中,该变量将它们信息插入 INSERT INTO 的值。也许是一个 for 循环?

INSERT INTO $table_name ($column_names) VALUES($q1, $q2, $q3)

所以它可能看起来像这样

INSERT INTO $table_name ($column_names) VALUES($combined_variables)

这样,我可以手动向 $q51 添加另一个变量,它会自动填充 VALUE。

这可能吗?也许是这样的(但这不起作用)

$combined_variables = '';
for( $i = 1; $i <= 50 $i++ ) { 
    $combined_variables .= 'q' . $i . ', ';
}
$combined_variables = substr($combined_variables, 0, -2); //minus 2 to remove the last space and comma

【问题讨论】:

  • 一个更好的主意是动态构建占位符,然后将它们加载到准备好的语句中
  • 至少摆脱这种荒谬并使用数组。然后只需implode

标签: php arrays variables for-loop


【解决方案1】:

这应该适合你:

(这里我从$q1开始,并将其分配给数组,直到下一个$qX没有设置)

<?php

    $combined_variables = [];
    $count = 1;

    while(isset(${"q" . $count})){
        $combined_variables[] = ${"q" . $count};
        $count++;
    }

?>

举个例子:

$q1 = 5;
$q2 = 2;

你最终会得到以下数组:

Array ( [0] => 5 [1] => 2 )

然后您可以像这样在查询中简单地使用它:

"INSERT INTO $table_name ($column_names) VALUES(" . "'" . implode("','", $combined_variables) . "'" . ")"

【讨论】:

    【解决方案2】:

    你可以像这样使用variable variables

    $combined_variables = array();
    for ($i = 1; $i <= 50 $i++) { 
        $var = 'q' . $i;
        $combined_variables[] = ${$var};
    }
    $combined_variables = implode(', ', $combined_variables);
    

    但是,如果您可以使用一个数组而不是 50 个变量,那么您的工作会容易得多。

    【讨论】:

    • 为什么要使用可变变量?我不明白你为什么需要它们?!
    • 他可以只将值放在数组中而不是变量中。
    • @Savadon 在您提出新问题之前,您现在无法在插入查询中使用变量$combined_variables
    • 看看另一个答案,在这件事上是正确的。
    猜你喜欢
    • 2016-01-14
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多