How to post array to a table by php and mysql?

Hello Experts,
I have a number of multiple choice questions which can be shown by the following code:

global $db;
$query = mysqli_query ($db, 'SELECT * FROM QUIZ ORDER BY RAND() LIMIT 5');
<form  name="submit-question" method="post" action="<?php PATH?>quiz.php" >
<input type="text" name="username" placeholder="username" autocomplete="off"/>
<?php 
$i = 1;
while ($questions = mysqli_fetch_array($query)){

?>
	<p> <?php echo $i++.") ".$questions['questions']; ?> </p>
	<input type="radio" id="<?php $questions['choice1']; ?>"  value = "<?php echo $questions['choice1']; ?>" name="a">
	<label for="<?php $questions['choice1']; ?>"> <?php echo $questions['choice1']; ?></label><br>
	
	<input type="radio" id="<?php $questions['choice2']; ?>"   value = "<?php echo $questions['choice2'];?>" name="a">
	<label for="<?php $questions['choice2'];; ?>"> <?php echo $questions['choice2']; ?></label><br>
	
	<input type="radio" id="<?php $questions['choice3']; ?>"  value = "<?php echo $questions['choice3'];?>" name="a">
	<label for="<?php $questions['choice3']; ?>"> <?php echo $questions['choice3']; ?></label><br>
	
	<input type="radio" id="<?php $questions['choice4']; ?>"  value = "<?php echo $questions['choice4'];?>" name="a">
	<label for="<?php $questions['choice4']; ?>"> <?php echo $questions['choice4']; ?></label><br>
	
	<input  type= "hidden" name = "<?php $questions['answer']; ?>" value="<?php echo $questions['answer']; ?>">
	<?php  ?>
	
	<?php } ?><br>
	<input type="submit" name="submit_quiz" value="submit" />

</form>

I would like to post my radio values to a table in my database. How to do that?
Another problem in my code is that I can just select 1 radio button for the whole questions.
Would you please help me to solve this?
Looking forward to your comments

radio buttons are not multiple choice.

if you want to save a real multiple choice (ie: checkbox)… then you probably need to implode the data to a delimited string before saving to the table.

1 Like

In my opinion it would be better to use HTML, PHP, JavaScript with Ajax (I use FETCH) and of course a Database table.

Here’s my main section of my HTML page:

<main id="content" class="checkStyle">
    <div class="displayStatus">
        <span id="clock"></span>
        <h4 class="displayTitle">Pepster's Online Trivia</h4>
        <p class="triviaInfo">I'm adding more categories to my online trivia game and hopefully make it appeal to more people! I am still keep the photography category,
        but I am adding two new categories (movie and space). I am going to make a better scoring feature and have daily challenges as well a monthly challenges!</p>
        <p>I'm still keeping the feature where a member can add questions to the online trivia database and be able to select the category of their liking, but the questions/answers will have to be approved by me first.</p>
        <p>You must register to become a Member and validate your email address before you can add questions. You don't have to add questions as you username will show up on the high scores table.</p>
        <div id="startBtn">
            <form id="game_category" action="game.php" method="post">
                <select id="category" class="select-css" name="category" tabindex="1">
                    <option selected disabled>Select a Category</option>
                    <option value="photography">Photography</option>
                    <option value="movie">Movie</option>
                    <option value="space">Space</option>
                </select>
            </form>
        </div>
    </div>

    <div id="quiz" class="displayMessage" data-username="<?= $username ?>">
        <div class="triviaContainer" data-records=" ">
            <div id="mainGame">
                <div id="current">Question No. <span id="currentQuestion"></span></div>
                <div id="triviaSection" data-correct="">
                    <div id="questionBox">
                        <h2 id="question">What is the Question?</h2>
                    </div>
                    <div id="buttonContainer"></div>
                </div>

                <div id="headerStyle" data-user="">
                    <div class="gauge">
                        <div class="gauge__body">
                            <div class="gauge__fill"></div>
                            <div class="gauge__cover">Power 100%</div>
                        </div>
                    </div>
                    <p id="score">0 Points</p>
                    <p id="percent">100% Correct</p>

                    <button id="next" class="nextBtn">Next</button>
                </div>

            </div>
        </div>
    </div>
    <div id="finalResult">
        <h2>Game Over!</h2>
        <p><?= $username ?> ended up with <span class="totalScore"></span> points and answered <span
                class="answeredRight"></span> right.</p>
        <a class="btn1" href="game.php" title="Quiz">Play Again?</a>
    </div>
</main>

Here’s a small section of my JavaScript file:

    /* Success function utilizing FETCH */
    const quizUISuccess = (parsedData) => {
        console.log('trivia data', parsedData);
        mainGame.style.display = 'grid';
        d.getElementById('content').scrollIntoView();

        //gameData = parsedData;


        gameData = parsedData.sort(() => Math.random() - .5); // randomize questions:
        totalQuestions = parseInt(gameData.length);
        createQuiz(gameData[gameIndex]);

    };

    /* If Database Table fails to load then answer a few hard coded Q&A */
    const quizUIError = (error) => {
        /*
         * If game database table fails to load then give a few questions
         * and answers, so that the game will still work properly.
         */
        failed = true;
        mainGame.style.display = 'grid';
        d.getElementById('content').scrollIntoView();
        console.log("Database Table did not load", error);
        gameData = [{
            "id": 1,
            "user_id": 1,
            "hidden": "no",
            "question": "[Blank] is the length of time when the film or digital sensor inside the camera is exposed to light, also when a camera's shutter is open when taking a photograph. The amount of light that reaches the film or image sensor is proportional to the [Blank].",
            "category": "photography",
            "answers": [
                "Shutter Speed or Exposure Time",
                "ISO",
                "",
                ""
            ]
        },
            {
                "id": 2,
                "user_id": 1,
                "hidden": "no",
                "question": "[Blank] was one of the earliest photographers in American history, best known for his scenes of the Civil War. He studied under inventor Samuel F. B. Morse, who pioneered the daguerreotype technique in America. [Blank] opened his own studio in New York in 1844, and photographed Andrew Jackson, John Quincy Adams, and Abraham Lincoln, among other public figures.",
                "category": "photography",
                "answers": [
                    "Robert Capa",
                    "Steve McCurry",
                    "Ansel Adams",
                    "Matthew Brady"
                ]
            }
        ]
        totalQuestions = gameData.length;
        //console.log(gameData[gameIndex]);
        createQuiz(gameData[gameIndex]);
    };

    /* create FETCH request */
    const createRequest = (url, succeed, fail) => {
        fetch(url)
            .then((response) => handleErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
    };

    /*
     * Start Game by Category
     */
    const selectCat = function (category) {

        const requestUrl = `${quizUrl}category=${category}`;

        createRequest(requestUrl, quizUISuccess, quizUIError);

    };

Here’s the cool part of the JavaScript Code:

/* Populate Question, Create Answer Buttons */
    const createQuiz = (gameData) => {

        startTimer(dSec);

        question.textContent = gameData.question;

        /*
         * Create Buttons then insert answers into buttons that were
         * create.
         */
        gameData.answers.forEach((value, index) => {


            let gameButton = buttonContainer.appendChild(d.createElement('button'));
            gameButton.id = 'answer' + (index + 1);
            gameButton.className = 'answerButton';
            gameButton.setAttribute('data-correct', (index + 1).toString());
            gameButton.addEventListener('click', clickHandler, false);
            /*
             * Don't Show Answers that have a Blank Field
             */
            if (value !== "") {
                gameButton.appendChild(d.createTextNode("📷 " + value));
            } else {
                gameButton.appendChild(d.createTextNode(" "));
                gameButton.style.pointerEvents = "none"; // Disable Click on Empty Field
            }
        });
    };

I won’t bore you will more of the coding, but you can find the whole thing here:

Feel free to copy it, use part of it or just get some ideas from it. The only thing I ask is if you do the first 2 give me credit somewhere in the coding.

1 Like

To post to your mysql table, you must of course first make that table. Then this works for me.
When your form is sent by the user, you assign the data to variables:

if(isset($_POST[‘sendAnswers’])){
// assign the answers to a variable
$surveyornr = $_POST[‘sn’];
$weeknr = $_POST[‘weeknr’];
$q1 = $_POST[‘G1’];
$q2 = $_POST[‘G2’];

I do some checking here make sure the student number is in the database, week number is correct, answers are not empty, then just insert the values with an INSERT

// if the student number exists, save the answers 
		if($stmt->rowCount() > 0){
		try{
			$mysql = 'INSERT INTO poll_1_data(surveyornr, weeknr, gender, choice) VALUES (?, ?, ?, ?)';
			$mystmt = $pdo->prepare($mysql);
			$mystmt->execute([$surveyornr, $weeknr, $q1, $q2]);
		}
		catch(PDOException $e){
			$_SESSION['error'] = $e->getMessage();
			//include '/surveys/poll_1.html.php'; 
			header('Location: /surveys/poll_1.html.php');
			exit();
			}

This is a link which Strider64 gave me, very useful. https://phpdelusions.net/pdo

1 Like

Thanks for your time and consideration;
Can you please check my code?

<form  name="submit-question" method="post" action="<?php PATH?>quiz.php" >
<?php 
$i = 1;
while ($questions = mysqli_fetch_array($query)){
$question = $questions['questions'];
$choice1 = $questions['choice1'];
$choice2 = $questions['choice2'];
$choice3= $questions['choice3'];
$choice4 = $questions['choice4'];
$answer = $questions['answer'];
?>
	<p> <?php echo $i++.") ".$question; ?> </p>
	<input type="hidden"  name="<?php echo $question ?>" value="<?php echo $question ?>">
	<input type="radio" id="<?php $choice1; ?>"  value = "<?php echo $choice1; ?>" name="<?php echo $question ?>">
	<label for="<?php $choice1; ?>"> <?php echo $choice1; ?></label><br>
	
	<input type="radio" id="<?php $choice2; ?>"   value = "<?php echo $choice2;?>" name="<?php echo $question ?>">
	<label for="<?php $choice2; ?>"> <?php echo $choice2; ?></label><br>
	
	<input type="radio" id="<?php $choice3; ?>"  value = "<?php echo $choice3;?>" name="<?php echo $question ?>">
	<label for="<?php $choice3; ?>"> <?php echo $choice3; ?></label><br>
	
	<input type="radio" id="<?php $choice4; ?>"  value = "<?php echo $choice4;?>" name="<?php echo $question ?>">
	<label for="<?php $choice4; ?>"> <?php echo $choice4; ?></label><br>
	
	<input  type= "hidden" name = "<?php $answer; ?>" value="<?php echo $answer; ?>">
	<?php  ?>
	
	<?php } ?><br>
	<input type="submit" name="sendAnswers" value="submit" />

</form>

My code populates the questions with multiple-choice questions for each question.
I would like to post questions, students answers and correct answers from the form and post to the table in my database.
So, I use the following code to do that,

if(isset($_POST['sendAnswers'])) {
	$username = mysqli_real_escape_string($db, $_POST['username']);
	if(empty($username)) {
		echo 'please enter the username'.'<br>';
	$question1 = $_POST[$question];	
	$your_answer = filter_has_var(INPUT_POST, $question);
	$correctanswer = $_POST[$answer];
	
				
	$sql = "INSERT INTO SCORE(USERNAME, QUESTION, YOURANSWER, CORRECTANSWER) VALUES('$username', '$question1', '$your_answer', '$correctanswer')";
		$run_sql = mysqli_query($db, $sql);
		if($run_sql){
			echo 'It has been added successfully!';
		}
	}
}

I see these errors in my browser:
Undefined variable: question
Undefined index
Would you please help me to solve the problem?
Thanks in advance;

When you look for inputs from forms, you usually have to check if they exist before you load them.
Loosely, check if it is there, if it is, get it, if not throw an error if needed.

if(isset($_POST["question"])) {
   $question1 = $_POST["question"];
}else{
   handle no entry 
}

Also, you should look at the source page of the page. View-source when looking at the page and see if the radio buttons are set up correctly. And, in your

if(isset($_POST['sendAnswers'])) {

section, you check for $_POST[$question], but, it is not set there. That is why you are getting the index error.

1 Like

Thanks for getting back to me,
I think the problem is that there are more than 1 value. What I mean is there 5 questions which are populated.

<form  name="submit-question" method="post" action="<?php PATH?>quiz.php" >
<input type="text" name="username" placeholder="" autocomplete="off"/>
<?php 
$i = 1;
while ($questions = mysqli_fetch_array($query)){
$question = $questions['questions'];
$choice1 = $questions['choice1'];
$choice2 = $questions['choice2'];
$choice3= $questions['choice3'];
$choice4 = $questions['choice4'];
$answer = $questions['answer'];
?>

There are 5 questions, 5 choice1, 5 choice2,…
But I would like to insert all of them into my table with a code like that:

if(isset($_POST['sendAnswers'])) {
	$username = mysqli_real_escape_string($db, $_POST['username']);
	if(empty($username)) {
	echo 'please enter the username'.'<br>';}
	if(isset($_POST[$question])) {
	$question1 = $_POST[$question];	
	}else{
		echo 'handle no entry';
	}

The $question need to have 5 values to be inserted in the table.
Moreover, when I check the source page, I see something like that

<p> 1) 3-2+5=? </p>
	<input type="hidden"  name="3-2+5=?" value="3-2+5=?">
	<input type="radio" id=""  value = "5" name="3-2+5=?">
	<label for=""> 5</label><br>
	
	<input type="radio" id=""   value = "7" name="3-2+5=?">
	<label for=""> 7</label><br>
	
	<input type="radio" id=""  value = "6" name="3-2+5=?">
	<label for=""> 6</label><br>
	
	<input type="radio" id=""  value = "8" name="3-2+5=?">
	<label for=""> 8</label><br>
	
	<input  type= "hidden" name = "" value="6">

I do not know, the radio button can get the value or not?
Looking forward to your comments

The question data needs an id (auto-increment primary index.) You would record the question id, the chosen value, along with the username (you should actually have a login system with username/password the produces a user id, that you would use when you store the submitted answers.)

Do not pass the answers through the form. You know what the answer is though the question id.

Because you are randomizing the questions, only generate a new set of questions if there is no active quiz, then store the question ids in a session variable to both indicate that a quiz is in progress and to ‘remember’ which questions are part of the quiz.

The form must submit both the question id and the chosen radio button value. To do this, use an array name for the radio buttons, such as ‘q[…]’, with the array index being the question id.

When the form is submitted any set of checked radio buttons will be set. Only a set of unchecked radio buttons won’t be set in the post data. You would loop over the question ids stored in the session variable. Any unset answers mean that no choice was made. If each question must be answered, you would setup a message for the user telling them that they must answer question x. Once all the questions have been answered, you would insert the rows into the score table.

Use a prepared query, prepared once before any looping, to insert the data.

You can save on the html for the <label> tags by simply putting them around the form field, no need for the for attribute and DOM ids.

1 Like

Thanks for your consideration.
Can you please help me with writing some code examples to be tangible for me.
Particularly this sentence:
To do this, use an array name for the radio buttons, such as ‘q[…]’, with the array index being the question id.
Thanks in advance

Sponsor our Newsletter | Privacy Policy | Terms of Service