Jump to content
neoxmel

Getting the values in Loop

Recommended Posts

Hello, guys ! i'm new in this forum and i seem to have a little problem in coding and i would really appreciate your help.
 
Here's my problem..
the values in QUESTIONS, ANS1, ANS2, ANS3, ANS4, CANS, ITEMS werent read, hence, it was not saved in the database.. but the other values were saved! now, i got confused..
 
here's the image of my code:

 

1_zpsbw7i0gig.jpg

 

2_zpsvejqdeyk.jpg

 

3_zpsmarv4tjw.jpg

 

and here's the result after clicking the SAVE button:

 

4_zpsvxfjktxx.jpg

Share this post


Link to post
Share on other sites

Do a dump of your $_POST array to see what is in there right after your script begins.

 

PS - it would be better if you posted the code, rather than screen prints.  Use the proper forum tags to wrap it.

Share this post


Link to post
Share on other sites

Please copy/paste code to your reply using the forum's code tags instead of posting a screenshot...a screenshot is very hard for us to work with.

 

actions ='createquestions.php'

 

This should be "action" not "actions".

Share this post


Link to post
Share on other sites

And it's “method”, not “metod”.

 

Besides that, your code is wide open to SQL injection attacks, uses deprecated database functions and obviously lacks errors handling. Even worse: It tells the user that the insertion was successful when that's clearly not the case.

 

I strongly recommend you switch to the PDO database interface and use prepared statements to safely pass user input to queries. You should also check for errors and give proper feedback.

Edited by Jacques1

Share this post


Link to post
Share on other sites

And it's “method”, not “metod”.

It took me a second to figure out where you were seeing that, which made me realize that OP has three separate forms.

 

Your $_POST indices are empty because the form that you actually submitted only has the submit button. Your other form elements need to be inside of the form that gets submitted for their data to be sent.

Share this post


Link to post
Share on other sites
<form method = "POST" name = "subjects" action ="createquestions.php">
Select Subject: <select name = "subjects">
  					<option value="English">English</option>
 					 <option value="Math">Math</option>
  					<option value="Science">Science</option>
  					<option value="Filipino">Filipino</option>
				</select> <br>

Multiple Choice: <input type = "text" name="MC"><br>
				
				 <input type = "submit" name = "confirm" value = "Confirm">
				 <a href = "home.php"><span>Cancel</span></a></center>

</form>


<?php

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

	$MC = $_POST['MC'];
	echo "<form method = 'POST' name = 'items' actions ='createquestions.php'>";
	$items = 1;
	echo "</form>";
	for ($x = 1; $x <= $MC; $x++) {
		echo "<form metod = 'POST' action = 'createquestions.php'>";
   		echo "Question Number $items:"; echo "<input type = 'text' name = 'questions' style='width: 500px'><br><br>";
   		echo "A. "; echo "<input type = 'text' name = 'ans1'>";
   		echo "B. "; echo "<input type = 'text' name = 'ans2'><br>";
   		echo "C. "; echo "<input type = 'text' name = 'ans3'>";
   		echo "D. "; echo "<input type = 'text' name = 'ans4'><br>";
   		echo "Correct Answer: "; echo "<input type = 'text' name ='cans'><br><br>";
   		$items++;		
   		echo "</form>";
	}

	echo "<form method = 'POST' action = 'createquestions.php'>";
	echo "<input type ='submit' name = 'save' value = 'Save'>";
	echo "</form>";

}

?>

<?php

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

$user_id = $_SESSION['id'];
$questions = $_POST['questions'];
$ans1 = $_POST['ans1'];
$ans2 = $_POST['ans2'];
$ans3 = $_POST['ans3'];
$ans4 = $_POST['ans4'];
$cans = $_POST['cans'];


	require_once('xcon.php');

		$query = "INSERT INTO mcq (mc_id, mc_num, user_id, questions, ans1, ans2, ans3, ans4, cans) 
				  VALUES ('NULL','$items','$user_id','$questions','$ans1','$ans2','$ans3','$ans4','$cans')";
		$result = mysql_query($query);

		if($result){
			echo 'Insert Success!';
		}
		else{
			echo 'Error';
		}

}

?>

I am so sorry for posting the screenshot.. actually, those codes are all in one form and this is the full code that i have

Share this post


Link to post
Share on other sites

No, this is not one form. Look at your code again: There's an empty form before the for loop (for whatever reason), then you create a sequence of forms with no submit button (for whatever reason), and finally you create yet another form with no data but a submit form (for whatever reason).

 

This obviously makes no sense. It seems what you actually want is one big form with multiple sections:

<form method="post" action="test.php">
    <fieldset>
        <legend>Question 1</legend>
        <p>What's the answer to question 1?</p>
        <input type="text" name="answer[0]">
    </fieldset>
    <fieldset>
        <legend>Question 2</legend>
        <p>What's the answer to question 2?</p>
        <input type="text" name="answer[1]">
    </fieldset>
    <fieldset>
        <legend>Question 3</legend>
        <p>What's the answer to question 3?</p>
        <input type="text" name="answer[2]">
    </fieldset>
    <input type="submit">
</form>

Note the bracket notation in the name attributes. This turns $_POST['answer'] into an array of the answers. Otherwise the values would overwrite each other.

Edited by Jacques1

Share this post


Link to post
Share on other sites

Your DB structure is not scale-able. You should have separate tables for questions and answers with a foreign key tying them together.

  • Like 1

Share this post


Link to post
Share on other sites

Additionally, I don't see you doing anything at all with the subjects posted from the form at the top of the page. When you do this up right, you will have another table called subjects or categories and pull from that for your drop down using the subject_id as the drop down value, not the subject description as you have now. Same thing for question types.

 

Also, there is no need to have the mc_id:value = null in your insert query. I am assuming you have it correctly set as auto-increment.

Edited by benanamen

Share this post


Link to post
Share on other sites

There are a lot of things that need to be revised and optimized. But I'd do this step-by-step, not all at once. Fixing the HTML and learning a new database interface and diving into database normalization and optimizing the queries might be a bit too much.

Share this post


Link to post
Share on other sites

I would go fixing the HTML and styling it with good old CSS first. That is what I would do.

 

For example I created an online trivia game and created where a user can add questions/answers to the database table. I first created a HTML Form styling it with CSS then I added the necessary PHP to it.

 

Here's the form:

    <form id="addQuestions"action="<?php echo $basename; ?>" method="post">
        <fieldset>
            <legend><?php echo isset($errorMsg) ? $errorMsg : "Add Question"; ?></legend>
            <input type="hidden" name="status" value="<?php echo ($user && $user->security_level === "sysop") ? "approved" : "pending"; ?>">
            <label class="questionLabel" for="question">Question</label>
            <textarea id="question" name="question" placeholder="Enter question here..."></textarea>
            <label class="questionData" for="answer1">Answer One</label>
            <input id="answer1" type="text" name="answer1" value="">
            <label class="questionData" for="answer2">Answer Two</label>
            <input id="answer2" type="text" name="answer2" value="">
            <label class="questionData" for="answer3">Answer Three</label>
            <input id="answer3" type="text" name="answer3" value="">
            <label class="questionData" for="answer4">Answer Four</label>
            <input id="answer4" type="text" name="answer4" value="">
            <label class="questionData" for="correct">Correct Answer</label>
            <input id="correct" type="text" name="correct" placeholder="Enter 1, 2, 3, or 4 for the correct answer!" value="">
            <input type="submit" name="submit" value="submit">
        </fieldset>
    </form>

as you can see not much in the way of PHP was added to it and the form also carried nicely over to the edit form (on a different web page)

    <form id="addQuestions"action="<?php echo $basename; ?>" method="post">
        <fieldset>
            <legend><?php echo isset($errorMsg) ? $errorMsg : "Edit Question"; ?></legend>
            <input type="hidden" name="id" value="<?php echo $total_ids[$_SESSION['page']]['id']; ?>">
            <label class="questionLabel" for="question">Question</label>
            <textarea id="question" name="question" placeholder="Enter question here..."><?php echo $record->question; ?></textarea>
            <label class="questionData" for="answer1">Answer One</label>
            <input id="answer1" type="text" name="answer1" value="<?php echo $record->answer1; ?>">
            <label class="questionData" for="answer2">Answer Two</label>
            <input id="answer2" type="text" name="answer2" value="<?php echo $record->answer2; ?>">
            <label class="questionData" for="answer3">Answer Three</label>
            <input id="answer3" type="text" name="answer3" value="<?php echo $record->answer3; ?>">
            <label class="questionData" for="answer4">Answer Four</label>
            <input id="answer4" type="text" name="answer4" value="<?php echo $record->answer4; ?>">
            <label class="questionData" for="correct">Correct Answer</label>
            <input id="correct" type="text" name="correct" value="<?php echo $record->correct; ?>">
            <label class="questionData" for="status">Status</label>
            <select id="status" <?php echo ($record->status === "approved") ? 'class="statusGreen"' : 'class="statusRed"'; ?> name="status">
                <?php
                    foreach ($statusArray as $key => $value) {
                        if ( $value === $record->status) {
                            echo '<option value="' . $record->status . '" selected>' . $record->status . '</option>';
                        } else {
                            echo '<option value="'. $value . '">' . $value . '</option>';
                        }
                    }
                ?>
            </select>
            <input type="submit" name="submit" value="submit">

        </fieldset>
    </form> 

as you can see a little more PHP was needed for the edit form and a few minor modifications need to be done to the HTML/CSS. My suggestion for you and/or anyone getting started in web design and development is get HTML/CSS and maybe JavaScript portion down pat first. Even if person considers him/her a developer, it's still very important to learn the design aspect of building a website even if someone else might be doing that portion. Like I already stated that is where I would start first. HTH John

Edited by Strider64

Share this post


Link to post
Share on other sites

Thank you so much for the help and suggestion, guys. I will make sure to take application on what you have taught me !

 

The flow of this program is that i want the user to input how many questions he/she would like to create and the system would automatically generate the inputted questions along with the answers. So, i ended up using this loop:

for ($x = 1; $x <= $MC; $x++) {
		echo "<form metod = 'POST' action = 'createquestions.php'>";
   		echo "Question Number $items:"; echo "<input type = 'text' name = 'questions' style='width: 500px'><br><br>";
   		echo "A. "; echo "<input type = 'text' name = 'ans1'>";
   		echo "B. "; echo "<input type = 'text' name = 'ans2'><br>";
   		echo "C. "; echo "<input type = 'text' name = 'ans3'>";
   		echo "D. "; echo "<input type = 'text' name = 'ans4'><br>";
   		echo "Correct Answer: "; echo "<input type = 'text' name ='cans'><br><br>";
   		$items++;		
   		echo "</form>";
	}

I know i have a lot of things to work with, but i'm planning to get this function first before designing the page.

Share this post


Link to post
Share on other sites

Creating multiple forms on the same page is not going to work. As soon as you submit one question/answer set the page is going to refresh. You would also need to identify which one of the many forms you submited (I assume the page createquestions.php you are submitting to is also the page you are creating the questions on. Might work with Ajax)

 

The opening and closing form element need to come out of the loop. You would then need to create the X amount of question/answer sets as an array and loop through it for your insert.

 

Simplest thing to do is just create one Q&A set at a time.

 

Here is similar example of what I mean

<?php
if ($_POST)
    {
    $db = new PDO("mysql:host=localhost;dbname=phphelp_form_array", "user", "pass");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $insertStmt = $db->prepare("INSERT INTO datatable (field1, field2) VALUES (?,?)");
    
    for ($i = 0; $i < count($_POST['field1']); $i++)
        {
        $insertStmt->execute(array(
            $_POST['field1'][$i],
            $_POST['field2'][$i]
        ));
        }
    }
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="post">
   <b>field1 1</b><br>
   <label>field1 <input type="text" name="field1[]"></label>
   <br>
   <label>field2 <input type="text" name="field2[]"></label>
   <br>
   <b>field1 2</b><br>
   <label>field1 <input type="text" name="field1[]"></label>
   <br>
   <label>field2 <input type="text" name="field2[]"></label>
   <input name="" type="submit" value="Submit">
</form>
Edited by benanamen

Share this post


Link to post
Share on other sites

Thank you so much for the help and suggestion, guys. I will make sure to take application on what you have taught me !

 

The flow of this program is that i want the user to input how many questions he/she would like to create and the system would automatically generate the inputted questions along with the answers. So, i ended up using this loop:

for ($x = 1; $x <= $MC; $x++) {
		echo "<form metod = 'POST' action = 'createquestions.php'>";
   		echo "Question Number $items:"; echo "<input type = 'text' name = 'questions' style='width: 500px'><br><br>";
   		echo "A. "; echo "<input type = 'text' name = 'ans1'>";
   		echo "B. "; echo "<input type = 'text' name = 'ans2'><br>";
   		echo "C. "; echo "<input type = 'text' name = 'ans3'>";
   		echo "D. "; echo "<input type = 'text' name = 'ans4'><br>";
   		echo "Correct Answer: "; echo "<input type = 'text' name ='cans'><br><br>";
   		$items++;		
   		echo "</form>";
	}
I know i have a lot of things to work with, but i'm planning to get this function first before designing the page.

 

What this is going to do is create a <form></form> block for every item. Since your submit button is in yet another, totally separate form, none of this data is ever going to make it to your PHP script. Only the form inputs that are inside of the <form></form> block that is submitted is going to get sent to the server.

Share this post


Link to post
Share on other sites

 

Only the form inputs that are inside of the <form></form> block that is submitted is going to get sent to the server.

 

Traditionally, yes. But HTML5 introduces the 'form' attribute for form elements, which allows for the form element to not be a child of the <form> tag.

 

Ex:

<form id="someform">
<input type="text" name="some_key" />
</form>

<input type="submit" form="someform" value="Submit the form" />

Share this post


Link to post
Share on other sites

And as none of the OP's forms have an id attribute, and none of his inputs have a form attribute, then this is irrelevant.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.