Nezdecek Nezdecek - 9 months ago 35
PHP Question

How to write to database with condition?

I'm beginner in PHP and I have problem write to database with condition. I have array with variables. And variables which have value 1 I need to save in to database. Some of the other variables can have value 0 or 5 and as I said 1 too.

Array with variables:

<?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'];
?>


and here is my attempt to write in database with condition (not work):

$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);


Can you help me please with correct code, please ?

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


And now I would like to have three tables. The first for values 1 "tableOK", second for value 5 "tableNOK" and third like info table "tableinfo".

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

Answer Source

For the new structure, assuming that the fields by default have value 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)
}

This checks all $qA01_... to $qA30_....