my php quizz application not working when inserting question - php

I have created a simple quizz application in php mysql. This application has two parts one is for students and other part is for admin, so in admin area I have created addquestion page here is the code
<form class="form-horizontal " action="addquestion.php" method="post" style="width:50%;margin:0 auto" id="addquestionform">
<div class="form-group">
<label class="control-label col-sm-3" for="q">Question</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="q" placeholder="Enter Question" name="q">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="ch1">Choice 1</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="ch1" placeholder="Enter choice 1" name="ch1">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="ch2">Choice 2</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="ch2" placeholder="Enter Choice 2" name="ch2">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="ch3">Choice 3</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="ch3" placeholder="Enter choice 3" name="ch3">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="ch4">Choice 4</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="ch4" placeholder="Enter choice 4" name="ch4">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="cn">Correct Choice</label>
<div class="col-sm-9">
<input type="number" class="form-control" id="cc" placeholder="Enter correct choice" name="cc">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="cn">Choose Catogry</label>
<div class="col-sm-9">
<select class="pull-left form-control" name="cat">
<?php while($row = mysqli_fetch_assoc($category)){ ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['subject_name']; ?> </option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-10">
<button type="submit" class="btn btn-default">Add Question</button>
</div>
</div>
</form>
for php part the code is as following where i get values from form for example the question, choice 1, choice 2, choice 3, choice 4 , correct choice, and the category where question and choices will be added .
if($_SERVER["REQUEST_METHOD"] == "POST"){
$question = $_POST['q'];
$choices[1] = $_POST['ch1'];
$choices[2] = $_POST['ch2'];
$choices[3] = $_POST['ch3'];
$choices[4] = $_POST['ch4'];
$correct = $_POST['cc'];
$cat = $_POST['cat'];
$query = mysqli_query($con,"insert into subject_questions values('','$question','$cat')");
if($query){
$questionid = mysqli_insert_id($con);
echo $questionid;
foreach($choices as $key => $value){
if($key == $correct){
$correct = 1;
}else{
$correct = 0;
}
$insert = mysqli_query($con,"insert into objectives values('','".$correct."','".$value."','".$questionid."')") or die(mysqli_error());
}
if($insert){
echo " <script> alert('question added successfully'); </script> ";
}else{
echo " <script> alert('question not added'); </script> ";
}
}
}
$category = mysqli_query($con,"select * from subject_category");
Now the problem is when the question and choices gets added to database only the first choice is selected as correct if its correct for example if some other choice is correct it does not put 1 as correct option there it only works for first choice I am guessing the problem lies here in this following part, here I used for each loop to loop through choices which comes from form and then stored inside $choices array so I check to see if key is match with the correct value entered in form if its correct then the correct variable gets 1 and if its not then its gets 0 . so as mentioned it only gets 1 if the first choice is correct but not for other choices .
foreach($choices as $key => $value){
if($key == $correct){
$correct = 1;
}else{
$correct = 0;
}
$insert = mysqli_query($con,"insert into objectives values('','".$correct."','".$value."','".$questionid."')") or die(mysqli_error());
}

The problem is that you're reusing the variable name $correct. At first it contains the number of the correct answer, but then you assign 1 or 0 to it. On the next iteration, when you do:
if ($key == $correct)
it no longer holds the number of the correct answer.
Use different variables.
foreach($choices as $key => $value){
if($key == $correct){
$is_correct = 1;
}else{
$is_correct = 0;
}
$insert = mysqli_query($con,"insert into objectives values('','".$is_correct."','".$value."','".$questionid."')") or die(mysqli_error());
}

It seems you are overriding the value of $correct inside the loop. Which failes for correct answer except 1; reomve overriding the variable $correct and rewrite the code.
instead of writing
foreach($choices as $key => $value){
if($key == $correct){
$correct = 1;
}else{
$correct = 0;
}
$insert = mysqli_query($con,"insert into objectives values('','".$correct."','".$value."','".$questionid."')") or die(mysqli_error());
}
you can write
foreach($choices as $key => $value){
if($key == $correct){
$insert = mysqli_query($con,"insert into objectives values('','1','".$value."','".$questionid."')") or die(mysqli_error());
}else{
$insert = mysqli_query($con,"insert into objectives values('','0','".$value."','".$questionid."')") or die(mysqli_error());
}
}
for example
if you are taking value of $correct as other than 1, after first iteration $correct resets to 0 and for the rest of the loop it carries value of 0.

Related

Getting the same data for all the records for editing and updating a record in php

I am having two different database tables questions and choices where i am inserting questions in one table and multiple choices in another table where questions table id is foreign key in choices table.
Questions:
Questions_number Text
1 What is HTML?
2 What is PHP?
Choices:
id question_number is_correct text
1 1 1 markup
2 1 0 Hyext
3 1 0 Hyper text markup language
4 2 0 hsdfd
5 2 0 frfwer
6 2 1 Hypertext Preprocessor
If i am trying to edit question number 1 then i need to fetch all the details of questions,Choices and correct option as well.But when i am trying to edit the record for choices as well i am getting the same data which i am getting for question.
HTML:
<?php session_start();
include 'includes/db.php';
$id = (int)$_GET['id'];
$sql = "SELECT * FROM questions q WHERE q.question_number = $id ";
$oppointArr =array();
$result = mysqli_query($mysqli,$sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result))
{
$oppointArr = $row;
echo "Text: " . $row["text"]. "<br>";
}
} else {
echo "0 results";
}
?>
<form class="form-horizontal" action="updatequestions.php" method="post" role="form">
<?php if(isset($msg)) {?>
<div class="<?php echo $msgclass; ?>" id="mydiv" style="padding:5px;"><?php echo $msg; ?></div>
<?php } ?>
<input type='hidden' value='<?=$id;?>' name='question_number'>
<h2>Edit A Question</h1>
<div class="form-group">
<label for="questionno" class="col-sm-2 control-label">Question Number</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['question_number'];?>"
name="question_number" id="question_number" readonly>
</div>
</div>
<div class="form-group">
<label for="question" class="col-sm-2 control-label">Question</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['text'];?>" name="question_text" id="question_text">
</div>
</div>
<input type='hidden' value='<?=$id;?>' name='id'>
<h2>Edit A Choice</h1>
<div class="form-group">
<label for="choice #1" class="col-sm-2 control-label">Choice #1</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['choice1'];?>" name="choice1" id="choice1">
</div>
</div>
<div class="form-group">
<label for="choice #2" class="col-sm-2 control-label">Choice #2</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['choice2'];?>" name="choice2" id="choice2">
</div>
</div>
<div class="form-group">
<label for="choice #3" class="col-sm-2 control-label">Choice #3</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['choice3'];?>" name="choice3" id="choice3">
</div>
</div>
<div class="form-group">
<label for="Correct Choice Number:" class="col-sm-2 control-label">Correct Choice Number:</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['is_correct'];?>" name="is_correct" id="is_correct">
</div>
</div>
<div class="col-sm-offset-2">
<button type="submit" class="btn btn-default" name="submit_user" id="subject">Submit</button>
<button type="cancel" class="btn btn-raised">Cancel</button>
</div>
</form>
Updatequestions:
<?php
include 'includes/db.php';
if(isset($_POST['submit_user']))
{
$questiontext = $_POST['question_text'];
$id=$_POST['question_number'];
$correct_choice = $_POST['correct_choice'];
$choices = array();
$choices[1] = $_POST['choice1'];
$choices[2] = $_POST['choice2'];
$choices[3] = $_POST['choice3'];
$choices[4] = $_POST['choice4'];
$choices[5] = $_POST['choice5'];
$query = "UPDATE questions SET text='$questiontext' WHERE question_number = $id";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row) {
foreach($choices as $choice => $value){
if($value != ''){
if($correct_choice == $choice){
$is_correct = 1;
} else {
$is_correct = 0;
}
$query = "UPDATE choices SET is_correct='$is_correct', text='$value' WHERE question_number=$id";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row){
continue;
} else {
die('Error : ('.$mysqli->errno . ') '. $mysqli->error);
}
}
}
$msg = 'Question has been added';
}
}
?>
If i try to update the record all the fields are updating with the same data.
WARNING: Do not create SQL statements by concatenating the data with SQL. Use prepared statements.
As for your problem, you use the foreign key of the question to update choices. The key is not the primary key of choices and is not unique. Try using the unique primary key for your SQL.
Instead of this:
$query = "UPDATE choices SET is_correct='$is_correct', text='$value' WHERE question_number=$id";
try this:
$query = "UPDATE choices SET is_correct='$is_correct', text='$value' WHERE id=$choice ";
But of course you should really try to do it all over again using prepared statements instead!
<form class="form-horizontal" action="updatequestions.php" method="post" role="form">
<?php if(isset($msg)) {?>
<div class="<?php echo $msgclass; ?>" id="mydiv" style="padding:5px;"><?php echo $msg; ?></div>
<?php } ?>
<input type='hidden' value='<?=$id;?>' name='question_number'>
<h2>Edit A Question</h1>
<div class="form-group">
<label for="questionno" class="col-sm-2 control-label">Question Number</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['question_number'];?>"
name="question_number" id="question_number" readonly>
</div>
</div>
<div class="form-group">
<label for="question" class="col-sm-2 control-label">Question</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="<?php echo $oppointArr['text'];?>" name="question_text" id="question_text">
</div>
</div>
<input type='hidden' value='<?=$id;?>' name='id'>
<h2>Edit A Choice</h1>
<?php
$choicesql = "SELECT * FROM `choices` WHERE question_number = $id ";
$ChoicetArr =array();
$choiceresult = mysqli_query($mysqli,$choicesql);
$inc=1;
$correctAns ="";
if (mysqli_num_rows($choiceresult) > 0)
{
while($rows = mysqli_fetch_array($choiceresult))
{
$ChoicetArr[] = $rows;
?>
<div class="form-group">
<label for="choice #<?php echo $inc;?>" class="col-sm-2 control-label">Choice #<?php echo $inc;?></label>
<div class="col-sm-5">
<input type="hidden" name="choice_id<?php echo $inc;?>" value="<?php echo $rows['id'];?>">
<input type="text" class="form-control" value="<?php echo $rows['text'];?>" name="choice<?php echo $inc;?>" id="choice<?php echo $inc;?>">
</div>
</div>
<?php
//print_r($rows);
if($rows['is_correct']=="1"){
$correctAns = '<input type="hidden" name="choice_id'.$inc.'" value="'.$rows['id'].'"><div class="form-group">
<label for="Correct Choice Number:" class="col-sm-2 control-label">Correct Choice Number:</label>
<div class="col-sm-5">
<input type="text" class="form-control" value="'.$inc.'" name="is_correct" id="is_correct">
</div>
</div>';
}
$inc++;
}
}
echo $correctAns;
?>
<div class="col-sm-offset-2">
<button type="submit" class="btn btn-default" name="submit_user" id="subject">Submit</button>
<button type="cancel" class="btn btn-raised">Cancel</button>
</div>
</form>
updatequestions.php
<?php
include 'includes/db.php';
if(isset($_POST['submit_user']))
{
$questiontext = $_POST['question_text'];
$id=$_POST['question_number'];
$correct_choice = $_POST['is_correct'];
$choices = array();
$choices[] = array("question"=>$_POST['choice1'], "answer"=>$_POST['choice_id1']);
$choices[] = array("question"=>$_POST['choice2'], "answer"=>$_POST['choice_id2']);
$choices[] = array("question"=>$_POST['choice3'], "answer"=>$_POST['choice_id3']);
$choices[] = array("question"=>$_POST['choice4'], "answer"=>$_POST['choice_id4']);
$choices[] = array("question"=>$_POST['choice5'], "answer"=>$_POST['choice_id5']);
$query = "UPDATE questions SET text='$questiontext' WHERE question_number = $id";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row)
{
$inc= 0;
foreach($choices as $choice => $value){
if(count($value)>0){
$answerInc = $choice+1;
if($correct_choice == $answerInc){
$is_correct = 1;
} else {
$is_correct = 0;
}
$text= $value['question'];
$answer = $value['answer'];
//echo "<br>".$text;
//print_r($value);
echo $answerInc;
echo "<br>";
echo $query = "UPDATE choices SET is_correct='$is_correct', text='$text' WHERE id=$answer";
$insert_row = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($insert_row){
continue;
} else {
die('Error : ('.$mysqli->errno . ') '. $mysqli->error);
}
}
$inc++;
}
$msg = 'Question has been Updated Successfully';
header("location:searchquestions.php");
exit;
}
}
?>

Multiple Insert Queries in PHP [duplicate]

This question already has answers here:
Why can't I run two mysqli queries? The second one fails [duplicate]
(2 answers)
Closed 6 years ago.
I am trying to create a php/html form which will insert results into a dog show database. The problem no matter what I do I get this error:
QUERY FAILED .You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO.
Here is the code for the page any help appreciated.
<?php
if(isset($_POST['create_show'])) {
//Insert Judges
$show_title = escape($_POST['show_title']);
$show_user = escape($_POST['show_user']);
$show_category_id = escape($_POST['show_category_id']);
$show_status = escape($_POST['show_status']);
// $show_image = escape($_FILES['show_image']['name']);
//$show_image_temp = escape($_FILES['image']['tmp_name']);
$show_tags = escape($_POST['show_tags']);
$show_content = escape($_POST['show_content']);
//$show_date = escape(date('d-m-y'));
//INSERT Judges
$judge_affix = escape($_POST['judge_affix']);
$judge_name = escape($_POST['judge_name']);
$judge_show = escape($_POST['show_idj']);
//Insert Dogs
$dog_name = escape($_POST['dog_name']);
$resultIDD = escape($_POST['resultIDD']);
//Insert Into Results
$class_name = escape($_POST['class_name']);
$placement = escape($_POST['placement']);
$award = escape($_POST['award']);
//move_uploaded_file($show_image_temp, "../images/$show_image" );
//Insert Shows
$query = "INSERT INTO shows (show_category_id, show_title, show_user, show_content, show_tags, show_status) VALUES ('$show_category_id','$show_title','$show_user','$show_content','$show_tags','$show_status');";
$query .= "INSERT INTO judges (judge_affix, judge_name) VALUES ('$judge_affix','$judge_name');";
$query .= "INSERT INTO dogs (dog_name, resultIDD) VALUES ('$dog_name','$resultIDD');";
$query .= "INSERT INTO result(class_name, placement,) VALUES ('$class_name','$placement')";
$create_show_query = mysqli_query($connection, $query);
confirmQuery($create_show_query);
$the_show_id = mysqli_insert_id($connection);
echo "<p class='bg-success'>Show Created. <a href='../show.php?s_id={$the_show_id}'>View Post </a> or <a href='shows.php'>Edit More Shows</a></p>";
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="show_title">Show Title</label>
<input type="text" class="form-control" name="show_title">
</div>
<div class="form-group">
<label for="category">Category</label>
<select name="show_category" id="">
<?php
$query = "SELECT * FROM categories";
$select_categories = mysqli_query($connection,$query);
confirmQuery($select_categories);
while($row = mysqli_fetch_assoc($select_categories )) {
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo "<option value='$cat_id'>{$cat_title}</option>";
}
?>
</select>
</div>
<div class="form-group">
<label for="users">Users</label>
<select name="post_user" id="">
<?php
$users_query = "SELECT * FROM users";
$select_users = mysqli_query($connection,$users_query);
confirmQuery($select_users);
while($row = mysqli_fetch_assoc($select_users)) {
$user_id = $row['user_id'];
$username = $row['username'];
echo "<option value='{$username}'>{$username}</option>";
}
?>
</select>
</div>
<!-- <div class="form-group">
<label for="title">Post Author</label>
<input type="text" class="form-control" name="author">
</div> -->
<div class="form-group">
<select name="show_status" id="">
<option value="draft">Show Status</option>
<option value="published">Published</option>
<option value="draft">Draft</option>
</select>
</div>
<div class="form-group">
<label for="show_tags">Show Tags</label>
<input type="text" class="form-control" name="show_tags">
</div>
<div class="form-group">
<label for="judge_name">Show Tags</label>
<input type="text" class="form-control" name="judge_name">
</div>
<div class="form-group">
<label for="judge_affix">Show Tags</label>
<input type="text" class="form-control" name="judge_affix">
</div>
<div class="form-group">
<label for="show_content">Show Content</label>
<textarea class="form-control " name="show_content" id="" cols="30" rows="5">
</textarea>
</div>
<div class="form-group">
<p>Minor Puppy Dog</p>
</div>
<div class="form-group">
<label for="dog_name">1st Dog Name</label>
<input type="text" class="form-control" name="dog_name">
</div>
<div class="form-group">
<input type="hidden" class="form-control" name="placement" value="1">
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="create_show" value="Publish Show">
</div>
</form>
The mysqli_query only executes one single query.
For executing multiple queries at once, you can use mysqli_multi_query.
Simply replace your mysqli_query with the mysqli_multi_query like so:
$create_show_query = mysqli_multi_query($connection, $query);

How to insert multiple rows of data [duplicate]

This question already has answers here:
Why can't I run two mysqli queries? The second one fails [duplicate]
(2 answers)
Closed 6 years ago.
I am trying to create a php/html form which will insert results into a dog show database. The problem no matter what I do I get this error:
QUERY FAILED .You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO.
Here is the code for the page any help appreciated.
<?php
if(isset($_POST['create_show'])) {
//Insert Judges
$show_title = escape($_POST['show_title']);
$show_user = escape($_POST['show_user']);
$show_category_id = escape($_POST['show_category_id']);
$show_status = escape($_POST['show_status']);
// $show_image = escape($_FILES['show_image']['name']);
//$show_image_temp = escape($_FILES['image']['tmp_name']);
$show_tags = escape($_POST['show_tags']);
$show_content = escape($_POST['show_content']);
//$show_date = escape(date('d-m-y'));
//INSERT Judges
$judge_affix = escape($_POST['judge_affix']);
$judge_name = escape($_POST['judge_name']);
$judge_show = escape($_POST['show_idj']);
//Insert Dogs
$dog_name = escape($_POST['dog_name']);
$resultIDD = escape($_POST['resultIDD']);
//Insert Into Results
$class_name = escape($_POST['class_name']);
$placement = escape($_POST['placement']);
$award = escape($_POST['award']);
//move_uploaded_file($show_image_temp, "../images/$show_image" );
//Insert Shows
$query = "INSERT INTO shows (show_category_id, show_title, show_user, show_content, show_tags, show_status) VALUES ('$show_category_id','$show_title','$show_user','$show_content','$show_tags','$show_status');";
$query .= "INSERT INTO judges (judge_affix, judge_name) VALUES ('$judge_affix','$judge_name');";
$query .= "INSERT INTO dogs (dog_name, resultIDD) VALUES ('$dog_name','$resultIDD');";
$query .= "INSERT INTO result(class_name, placement,) VALUES ('$class_name','$placement')";
$create_show_query = mysqli_query($connection, $query);
confirmQuery($create_show_query);
$the_show_id = mysqli_insert_id($connection);
echo "<p class='bg-success'>Show Created. <a href='../show.php?s_id={$the_show_id}'>View Post </a> or <a href='shows.php'>Edit More Shows</a></p>";
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="show_title">Show Title</label>
<input type="text" class="form-control" name="show_title">
</div>
<div class="form-group">
<label for="category">Category</label>
<select name="show_category" id="">
<?php
$query = "SELECT * FROM categories";
$select_categories = mysqli_query($connection,$query);
confirmQuery($select_categories);
while($row = mysqli_fetch_assoc($select_categories )) {
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo "<option value='$cat_id'>{$cat_title}</option>";
}
?>
</select>
</div>
<div class="form-group">
<label for="users">Users</label>
<select name="post_user" id="">
<?php
$users_query = "SELECT * FROM users";
$select_users = mysqli_query($connection,$users_query);
confirmQuery($select_users);
while($row = mysqli_fetch_assoc($select_users)) {
$user_id = $row['user_id'];
$username = $row['username'];
echo "<option value='{$username}'>{$username}</option>";
}
?>
</select>
</div>
<!-- <div class="form-group">
<label for="title">Post Author</label>
<input type="text" class="form-control" name="author">
</div> -->
<div class="form-group">
<select name="show_status" id="">
<option value="draft">Show Status</option>
<option value="published">Published</option>
<option value="draft">Draft</option>
</select>
</div>
<div class="form-group">
<label for="show_tags">Show Tags</label>
<input type="text" class="form-control" name="show_tags">
</div>
<div class="form-group">
<label for="judge_name">Show Tags</label>
<input type="text" class="form-control" name="judge_name">
</div>
<div class="form-group">
<label for="judge_affix">Show Tags</label>
<input type="text" class="form-control" name="judge_affix">
</div>
<div class="form-group">
<label for="show_content">Show Content</label>
<textarea class="form-control " name="show_content" id="" cols="30" rows="5">
</textarea>
</div>
<div class="form-group">
<p>Minor Puppy Dog</p>
</div>
<div class="form-group">
<label for="dog_name">1st Dog Name</label>
<input type="text" class="form-control" name="dog_name">
</div>
<div class="form-group">
<input type="hidden" class="form-control" name="placement" value="1">
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="create_show" value="Publish Show">
</div>
</form>
The mysqli_query only executes one single query.
For executing multiple queries at once, you can use mysqli_multi_query.
Simply replace your mysqli_query with the mysqli_multi_query like so:
$create_show_query = mysqli_multi_query($connection, $query);

PHP not inserting multiple data in MySQL table

I am trying to build a multiple choice exam portal. It's working fine but when I am adding a question in my add.php file it get inserted but the choices of the question is not inserted in database
Here is my database:
Choices table:
Questions table:
Here is my code for add.php
<?php include 'includes/header.php'; ?>
<?php include 'config/config.php'; ?>
<?php include 'lib/Database.php'; ?>
<?php
$db = new Database();
if (isset($_POST['submit'])) {
//Grab Post Data
$question_number = $_POST['question_number'];
$question_text = $_POST['question_text'];
$correct_choice = $_POST['correct_choice'];
$choices = array();
$choices[1] = $_POST['choice1'];
$choices[2] = $_POST['choice2'];
$choices[3] = $_POST['choice3'];
$choices[4] = $_POST['choice4'];
//Insert question into database
$query = "INSERT INTO `questions`(question_number, text) VALUES('$question_number','$question_text')";
$insert_row = $db->insert($query);
//validate
if ($insert_row) {
foreach ($choices as $choice => $value) {
if ($value != '') {
if ($correct_choice == $choice) {
$is_correct = 1;
} else {
$is_correct = 0;
}
//Choice Query
$query = "INSERT INTO `choices`(question_number,is_correct,text) VALUES('$question_number','$is_correct',
'$value')";
//insert row
$insert_row = $db->insert($query);
if ($insert_row) {
continue;
} else {
die($mysqli->error);
}
}
}
}
}
$query1 = "SELECT * FROM `questions`";
$result = $db->select($query1);
$total = $result->num_rows;
$next = $total + 1;
?>
<form class="form-horizontal" action="signup.php" method="POST">
<fieldset>
<div id="legend">
<legend class="text-center">Add Questions</legend>
</div>
<div class="control-group">
<label class="control-label" for="username">Question Number</label>
<div class="controls">
<input name="question_number" value="<?php echo $next; ?>" placeholder="" class="form-control input-lg" type="number"/>
</div>
</div>
<div class="control-group">
<label class="control-label" for="text">Question Text</label>
<div class="controls">
<input name="text" placeholder="" class="form-control input-lg" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label" for="choice1">#Choice 1</label>
<div class="controls">
<input name="choice1" placeholder="" class="form-control input-lg" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">#Choice 2</label>
<div class="controls">
<input id="choice2" name="choice2" placeholder="" class="form-control input-lg" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">#Choice 3</label>
<div class="controls">
<input id="choice3" name="choice3" placeholder="" class="form-control input-lg" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">#Choice 4</label>
<div class="controls">
<input id="username" name="choice4" placeholder="" class="form-control input-lg" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label" for="username">Correct Choice Number</label>
<div class="controls">
<input id="username" name="correct_choice" placeholder="" class="form-control input-lg" type="number"/>
</div>
</div>
<input type="submit" name="submit" class="btn btn-block btn-primary" value="Submit" class="submit"/>
</fieldset>
</form>
<?php include 'includes/footer.php';?>
Now only the question is adding in the database but not the choices.
The syntax appears to be correct, but you can delete simple quotes around numbers. In addition, it's better to make one request to insert all choices.
//validate
if ($insert_row) {
$values = [];
foreach ($choices as $choice => $value) {
if ($value == '')
continue;
$is_correct = $correct_choice == $choice ? 1 : 0;
$values[] = "($question_number, $is_correct, '$value')";
}
if (count($values) > 0)
{
$query = "INSERT INTO choices (question_number, is_correct, text) VALUES ".implode(',', $values);
$insert_row = $db->insert($query);
if (!$insert_row)
die($mysqli->error);
}
}
And your variables $value and $question_number come from $_POST variable, you have to use prepared statement to protect your query from SQL injection.

Checkbox(es) clicked will show another input field, how to put it in the database?

I have a working code where if I select multiple checkboxes, it will be saved in the database in separate rows (it is required). Also, I have a working code where if it checks a certain checkbox, another input field will show. Now, how do I save the checkbox value along the other input field that comes with it in the database?
This is the form:
<form class="form-horizontal form-label-left" name = "documentRequest" enctype="multipart/form-data" role="form" method="post" novalidate>
<div class = "second">
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12"> Document Request(s) <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="checkbox" name="docs[]" id="doc1" value="Certificate of Residency" /> Certificate of Residency
<br/>
<div class = "col-xs-3">
<input name="d1" class="form-control col-md-7 col-xs-12" required="required" type="number">
</div>
<div class = "clearfix"></div>
<input type="checkbox" name="docs[]" id="doc2" value="Barangay Clearance" /> Barangay Clearance
<br />
<div class = "col-xs-3">
<input name="d2" class="form-control col-md-7 col-xs-12" required="required" type="number">
</div>
<div class = "clearfix></div>
</form>
This is my php code (this works; it saves multiple checkbox values):
<?php
include 'config.php';
if (isset($_POST['documentRequest']))
{
$chkbox = $_POST['docs'];
$i = 0;
foreach($chkbox as $chk1)
{
$query = mysqli_query($conn, "INSERT INTO document(typeOfDoc) VALUES ('$chk1');");
}
echo "Checkbox value is successfully submitted.";
} ?>
This is the picture of the form:
Can you all please help me? How do I save this? Thank you.
Try this
<?php
include 'config.php';
if (isset($_POST['documentRequest']))
{
$chkbox = $_POST['docs'];
$i = 0;
foreach($chkbox as $chk1)
{
if($chk1=='Certificate of Residency')
{
$chek_val=$_POST['d1'];
}
else if($chk1=='Barangay Clearance')
{
$chek_val=$_POST['d2'];
}
$query = mysqli_query($conn, "INSERT INTO document(typeOfDoc,docval) VALUES ('$chk1','$chek_val');");
}
echo "Checkbox value is successfully submitted.";
} ?

Categories