good day!

Please help me here, I need to count the record according to my condition but with my code it only counts the last record in the table in MySql. Here is my code.. Thanks!

<?php
//establishing connection
mysql_connect("localhost", "abc", "bbb") or die(mysql_error());
$submit = $_POST['submit'];
$cancel = $_POST['cancel'];			
$answer = $_POST['answer'];	

//connecting to the database
mysql_select_db("xxx") or die(mysql_error());

			$result = mysql_query("SELECT * FROM qqq") or die(mysql_error()); 
			echo "<center><font size=2 face=Arial><b>qwerty</b></font></center><br/>";
			echo "<font size=1 face=Arial><b>Type in True if the statement is correct and False if otherwise.</b></font><br/><br/>";		
			echo "<table cellpadding = 1><tr><th><font size = 1>Answer</th><th><font size = 1>Question</th></tr>";
			while($row = mysql_fetch_array($result))
			{
				echo "<tr><td>";  
				echo "<font size = 1><input name='answer' type='text'>";		
         		echo "</font></td><td><font size = 1>";	
				$question = $row['question'];
				$answer = $row['answer'];
				$id = $row['questionid'];
				echo $question;
      			echo "</td></tr>"; 
			}
			echo "</table>";
			echo "</font></center>";
if ($cancel == 'Cancel')
	{
		echo "<META HTTP-EQUIV=REFRESH CONTENT='0; URL='>";
		exit;
	}
	
else if ($submit == 'Submit')
	{
	$date = date("F d, Y");
	$count = mysql_query("SELECT COUNT(*) FROM qqq WHERE question = '$question' && answer = '$answer' && questionid = '$id'") or die(mysql_error());
	$score = mysql_result($count,0,0);
	
	mysql_query("INSERT INTO results (idnumber, fullname, score, exam_title, exam_dept, exam_date) 
					VALUES ('$pangalanUser','$fullname', '$score','Awareness and Reminders', 'ECM Production', '$date')") 
						or die(mysql_error());  					
	echo "<script>alert('Your score is $score! Score is already saved.')</script>";
	echo "<META HTTP-EQUIV=REFRESH CONTENT='0; URL='>";
	}
?>

Dani AI

Generated

Short version: the page is rendering many identical inputs and then using variables filled from the last database row, so the script ends up checking only one question. spotted that the loop was assigning DB values into the same PHP variables instead of using the posted answers. Fix by giving each input a unique key (use an array indexed by question id), then compare the posted array to the real answers you fetch from the database.

Example form field pattern (render one per question):

<!-- render per question; replace 123 with the real question id -->
<input type="text" name="answers[123]" maxlength="200">

Processing outline (server side):

$userAnswers = $_POST['answers'] ?? [];   // array: questionid => user text
$correct = fetchAnswersFor(array_keys($userAnswers)); // DB: map questionid => correct answer
$score = 0;
foreach ($userAnswers as $qid => $text) {
    $text = trim(strtolower($text));
    if (isset($correct[$qid]) && $text === strtolower(trim($correct[$qid]))) {
        $score++;
    }
}

Notes and cautions: fetch the correct answers in one query (by the list of ids) rather than re-querying inside a loop. Validate that posted keys are numeric question ids so users cannot fake extra answers. Normalize answers (trim, case-fold, optionally strip punctuation) so minor formatting differences do not mark correct answers wrong. Do not use the old mysql_* extension — use PDO or mysqli with prepared statements to avoid SQL injection when you insert the final score. Finally, compute and store the single integer $score and save that with a prepared INSERT; this is safer and clearer than trying to count matches with per-question variables after the rendering loop.

This approach addresses the variable-overwrite problem identified and gives a reliable way to collect and count every answer.

Recommended Answers

All 20 Replies

Try this.

$count = mysql_query("SELECT * FROM qqq WHERE question = '$question' && answer = '$answer' && questionid = '$id'") or die(mysql_error());
	$score = mysql_num_rows($count);

i tried your code but it always display that the score is 1.

what shall i do?

I see the bug. Try the following.

$count = mysql_query("SELECT * FROM qqq WHERE question = '$question' AND answer = '$answer' AND questionid = '$id'") or die(mysql_error());
	$score = mysql_num_rows($count);

same output goes..the score is 1 :(

Well your where clause is filtering it to 1 row. I would suggest changing the where clause to match what you need. At the moment it looks like the where clause is designed to match 1 row and that could be your problem.

do you have any suggestion of how will i solve this.

im really having a hard time..

thanks.

Well how are you trying to filter it. Are you trying to filter it to one row because that is how it is currently set up. The items after the word WHERE will need changing to match your needs. What is the basic theory behind how it needs to be filtered and what is the column structure. If you can explain those two things I may be able to piece together a mysql query for ya.

this code is for an online exam, so i need to display all the questions from the mysql table. from that i inserted a text box where the examinee will input his answer. the exam is identification in type. i named the text box, answer and the displayed question, question.

when the examinee submits the answers, the code will count the correct answers that the examinee got.

Then is this what you need?

$count = mysql_query("SELECT * FROM qqq") or die(mysql_error());

im writing the where clause so i can count the correct answers that the examinee got, his answers must match to the answers from the table.

Perhaps one of the following two.

$count = mysql_query("SELECT * FROM qqq WHERE question = '$question' AND answer = '$answer'") or die(mysql_error());
$count = mysql_query("SELECT * FROM qqq WHERE answer = '$answer'") or die(mysql_error());

i think the problem is the code doesn't get the value of each answers from the text box and check the if it matches in the table.

it displays the same...

i tried everthing..

I just checked your script and found $question, $answer and $id all equals the value of the last row. This is because of the following section.

while($row = mysql_fetch_array($result))
			{
				echo "<tr><td>";  
				echo "<font size = 1><input name='answer' type='text'>";		
         		echo "</font></td><td><font size = 1>";	
				$question = $row['question'];
				$answer = $row['answer'];
				$id = $row['questionid'];
				echo $question;
      			echo "</td></tr>"; 
			}

Now is $answer meant to be $_POST or $_GET etc. That would be your problem.

from that, what do i need to do?

is there an alternative of that code?

Well $answer. it equals $row in the loop of the table resulting of $answer being the value of the last row of the table. But what I'm saying is shouldn't $answer and it's surrounding variables be replaced with the user input?

so how do i get the input of the user from the loop?

I think you should read a forms tutorial as some of the things your unsure about are the most vital things to know in php.

ok thanks! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.