I am new here and should make it clear that I am not a computer programmer, just doing this for a hobby. As a result, I understand that my codes are not perfect but just wondering how to add the following array into a database.
At the moment, only one array is being inserted. I am trying to follow a php tutorial on how to do a php quiz but the person did not use implode() or serialize(). How can I insert separate rows? I hope that I have formatted it correctly.
<?php
include_once 'includes/dbh.php';
include_once 'header.php';
$sql = "SELECT * FROM users WHERE user_uid = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "s", $_SESSION['u_uid']);
//Run parameters inside database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
if ($row['admin'] == 0) {
header("Location: header.php?add=notadmin");
exit;
} else {
if (isset($_POST['submit'])) {
include_once 'includes/dbh.php';
$question_number = $_POST['question_number'];
$question_text = $_POST['question_text'];
$correct_choice = $_POST['correct_choice'];
//Choices array
$choices = array();
$choices[1] = $_POST['choice1'];
$choices[2] = $_POST['choice2'];
$choices[3] = $_POST['choice3'];
$choices[4] = $_POST['choice4'];
$correct_choice = $_POST['correct_choice'];
$sql2 = "INSERT INTO questions (question_number, text) VALUES (?,?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "is", $question_number, $question_text);
//Run parameters inside database
mysqli_stmt_execute($stmt);
foreach($choices as $choice => $value) {
if ($value != '') {
if ($correct_choice == $choice) {
$is_correct = 1;
} else {
$is_correct = 0;
}
// Choice query
$sql3 = "INSERT INTO choices (question_number, is_correct, text) VALUES (?,?,?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql3)) {
echo 'SQL statement failed';
} else {
//Bind parameters to the placeholder
mysqli_stmt_bind_param($stmt, "iis", $question_number, $is_correct, $value);
mysqli_stmt_execute($stmt);
}
header("Location: quiz.php?add=success");
exit();
}
}
}
}
}
}
Here is the output of print_r($choices):
Array (
[question_number] => 2
[question_text] => how many beat is a crotchet?
[choice1] => one
[choice2] => two
[choice3] => three
[choice4] => four
[correct_choice] => 1
[submit] => submit
)
I am wondering why all the $value are being shown when I echo $value;; only the first variable is outputting anything.
I am also wondering... what is the equivalent in writing $result = mysqli->query(); in procedural mysqli? Is this the same as writing $result = mysqli_stmt_execute($stmt);?