如何用条件写入数据库?

时间:2017-03-10 11:25:58

标签: php arrays database mysqli conditional-statements

我是PHP的初学者,我有问题写入数据库有条件。我有变量数组。值为1的变量我需要保存到数据库中。其他一些变量的值可以是0或5,正如我所说的那样。

包含变量的数组:

<?php session_start();    
        $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'];

        $qA02_1 = $_SESSION['qA02_1'];     
        $qA02_2 = $_SESSION['qA02_2'];
        $qA02_3 = $_SESSION['qA02_3'];
        $qA02_4 = $_SESSION['qA02_4'];
        $qA02_5 = $_SESSION['qA02_5'];

        $qA03_1 = $_SESSION['qA03_1'];     
        $qA03_2 = $_SESSION['qA03_2'];
        $qA03_3 = $_SESSION['qA03_3'];
        $qA03_4 = $_SESSION['qA03_4'];
        $qA03_5 = $_SESSION['qA03_5'];

        $qA04_1 = $_SESSION['qA04_1'];     
        $qA04_2 = $_SESSION['qA04_2'];
        $qA04_3 = $_SESSION['qA04_3'];
        $qA04_4 = $_SESSION['qA04_4'];
        $qA04_5 = $_SESSION['qA04_5'];

        $qA05_1 = $_SESSION['qA05_1'];     
        $qA05_2 = $_SESSION['qA05_2'];
        $qA05_3 = $_SESSION['qA05_3'];
        $qA05_4 = $_SESSION['qA05_4'];
        $qA05_5 = $_SESSION['qA05_5'];
?>

这是我尝试在数据库中写入条件(不工作):

 $connect = mysqli_connect('localhost', 'root', 'pass', 'database');
        $varValue = 1;
        $values = [];
        foreach([1,2,3,4,5] as $index) {
           if(['$qA01_'.$index] == 1) {
               $values[] = "('$qA01_{$index}')";
           };
        }
        $query = "INSERT INTO table ($varValue) VALUES ". implode(',',$values);  
        mysqli_query($connect, $query);

请问您能用正确的代码帮我吗?

Here is old table where are together value 0, 1, 5.

现在我想要三张桌子。第一个用于值1“tableOK”,第二个用于值5“tableNOK”,第三个用于信息表“tableinfo”。

Three new tables created in Excel and my wishes in phpMyAdmin (my proposal)

1 个答案:

答案 0 :(得分:0)

对于新结构,假设默认情况下字段的值为0:

 $connect = mysqli_connect('localhost', 'root', 'pass', 'database');
if (mysqli_connect_errno())
    echo "Error connection: (" . mysqli_connect_errno().")";

$values = [];
$fields = [];
for($i=1;$i<=30;$i++)
{
    foreach([1,2,3,4,5] as $index) 
    {
        if(${'qA'.str_pad($i, 2, "0", STR_PAD_LEFT).'_'.$index} == 1) 
        {
            $values[] = ${'qA'.str_pad($i, 2, "0", STR_PAD_LEFT).'_'.$index};
            $fields[] = 'qA'.str_pad($i, 2, "0", STR_PAD_LEFT).'_'.$index;
        }
    }
}
$query = "INSERT INTO tableOK(".implode(',',$fields).") VALUES (". implode(',',$values).")";

if( !  mysqli_query($connect, $query))
{
    echo "Error query: ".mysqli_error($connect)
}

这会检查所有$qA01_...$qA30_...