Ichigo
Ichigo

Reputation: 3

PHP Insert array into MySQL database get data from checkbox

HTML Input

<input type="checkbox" value="1" name="que[10][1]">
<input type="checkbox" value="2" name="que[10][2]">
<input type="checkbox" value="3" name="que[10][3]">
...
<input type="checkbox" value="40" name="que[10][40]">

PHP submit

$submit = $_POST["que"];

I have the following array I want to store in my database :

Array
(
    [10] => Array
        (
            [0] => 26
            [1] => 27
            [2] => 28
            [3] => 29
            [4] => 30
            [5] => 31
        )

)

How can I convert to insert statement output following as below :

INSERT INTO `tb_answers` (`question_id`, `answer`) VALUES(10,26),(10,27),(10,28),(10,29),(10,30);

Here is my code :

$submit = $_POST['que'];

$all_values = [];

$sql_submit_form = "INSERT INTO `tb_answers` (`question_id`, `answer`) VALUES";

foreach ($submit as $question_id => $choise) {
   
    $row_values = [];
    foreach ($choise as $choise_data => $s_value) { 
        $row_values[] = "'" . $question_id . "'"; // question_id
        $row_values[] = "'" . $s_value . "'"; // answer

    }
    $all_values[] = '(' . implode(',', $row_values) . ')';
}
$sql_submit_form .= implode(',', $all_values);

echo $sql_submit_form;

Output :

INSERT INTO `tb_answers` (`question_id`, `answer`) VALUES('10','27','10','28','10','29','10','30','10','31','10','32')

Upvotes: 0

Views: 67

Answers (2)

Beowolve
Beowolve

Reputation: 558

As already mentioned, you construct your SQL query wrong. SQL Injection is a thing, you need to use '?' placeholders if you plan to use this in production environments. Your desired output can be generated like that:

$row_values = [];
foreach ($submit as $question_id => $choise) {
    foreach ($choise as $choise_data => $s_value) {
        $row_values[] = "(". $question_id .",".$s_value . ")";
    }
}
$sql_submit_form .= implode(',', $row_values);

Upvotes: 0

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146450

You only need to clean up what you already have. There's also no need to inject raw data into your SQL code, that only makes code harder to maintain (apart from insecure):

$params = $clauses = [];
foreach ($submit as $question_id => $choices) {
    foreach ($choices as $choice_id) {
        $clauses[] = '(?, ?)';
        $params[] = $question_id;
        $params[] = $choice_id;
    }
}
$sql = 'INSERT INTO `tb_answers` (`question_id`, `answer`) VALUES ' . implode(', ', $clauses);

Then feed $params to a prepared statement and you'll be done.

Upvotes: 1

Related Questions