如何从数组中获取所有数字1并将其保存到数据库中?

时间:2017-03-08 20:56:45

标签: php mysql mysqli

我有$qA01_1$qA30_5的150个变量。每个会话随机变量的值可以是0或1或5。我想选择所有值为1的变量并保存到数据库中(表“一”)。值0(表“0”)和5(表“5”)相同。你能帮我解决一下我的代码吗?对不起我的英语。希望一切都清楚。

这是我缩短的数组:

<?php
session_start();
// variables from
$qA01_1 = $_SESSION['qA01_1'];     
$qA01_2 = $_SESSION['qA01_2'];
$qA01_3 = $_SESSION['qA01_3'];
$qA01_4 = $_SESSION['qA01_4'];
$qA01_5 = $_SESSION['qA01_5']
// up to
$qA30_1 = $_SESSION['qA30_1'];     
$qA30_2 = $_SESSION['qA30_2'];
$qA30_3 = $_SESSION['qA30_3'];
$qA30_4 = $_SESSION['qA30_4'];
$qA30_5 = $_SESSION['qA30_5'];
?>

我的缩短代码,仅适用于$qA01_1变量$qA01_5(不工作):

<?php
$connect = @MySQL_Connect('localhost', 'root', ' ', 'db');
$vars = get_defined_vars();
foreach ($vars as $varName => $varValue) {
  if (strpos($varName, 'qA') !== false && $varValue === 1) {
    mysqli_query($connect, "INSERT INTO one ((ifnull(qA01_1, 0) + ifnull(qA01_2, 0) + ifnull(qA01_3, 0) + ifnull(qA01_4, 0) + ifnull(qA01_5, 0) ) VALUES ('" .$varName. "', '" .$varValue. "')");
  }
}  
?>

1 个答案:

答案 0 :(得分:0)

您的问题出在您的mysql查询中:

INSERT INTO one 
    ((ifnull(qA01_1, 0) + ifnull(qA01_2, 0) + ifnull(qA01_3, 0) + ifnull(qA01_4, 0) + ifnull(qA01_5, 0) ) 
VALUES 
    ('" .$varName. "', '" .$varValue. "')

Insert语法为:

INSERT INTO table_name 
    ( field1, field2,...fieldN )
VALUES
    ( value1, value2,...valueN );

然后我建议一个foreach:

$varValue = 1;
$values = [];
foreach([1,2,3,4,5] as $index) { // or use range(1,5)
   if($_SESSION['qA01_'.$index] == 1) {
       $values[] = "('qA01_{$index}')";
   };
}
$query = "INSERT INTO one (varValue) VALUES ". implode(',',$values);  
mysqli_query($connect, $query);