I am printing question number with the correct answer as 1 and wrong answer as 0.

Now I would like to count how many correct answers for each question.

Example of this:
Question number: 8
00110

For this example there are two correct answer.

$scoree = 0;
		$intt = 0;
		$sqlll=question();
			while($infoo = mysql_fetch_array( $sqlll)) {
		
	  
			echo "<hr><br><strong>{$infoo['Que_ID']}</strong><br />\n";
			$_Session1=$infoo['Que_ID'];
  
		$man=count($_Session1);
			while($infooo = mysql_fetch_array( $man)) {
				$answer1 = $infooo['Que_Answer1'] == $infooo['Ans_Answer1'];
				$answer2 = $infooo['Que_Answer2'] == $infooo['Ans_Answer2'];
				$answer3 = $infooo['Que_Answer3'] == $infooo['Ans_Answer3'];
				$answer4 = $infooo['Que_Answer4'] == $infooo['Ans_Answer4'];
				if ( $answer1 && $answer2 && $answer3 && $answer4)
				{
				echo ("1");
				
	
				}
	
				else
				{
				echo ("0");
				
				}
	
			}
			}

Dani AI

Generated

Two straightforward options depending on where you want the work done: in PHP (if you already have the 0/1 string or array) or in the database (faster for many rows). As hinted, keep the answer fields numeric (TINYINT or INT) so sums work correctly.

If you already build a 0/1 string like 00110, count the ones in PHP:

$bits = '00110';
$correct = substr_count($bits, '1');
echo $correct; // 2

If you produce each comparison in a loop, cast the boolean to an int and sum the values (safer than trying to use count() on a scalar):

$totals = [];
$totals[] = (int)($given == $expected); // yields 1 or 0
...
echo array_sum($totals);

If you prefer the database to do the counting (recommended for large sets), aggregate with SUM/CASE or COUNT+GROUP BY so the server returns one row per question with a correct-count. For example, sum one-per-correct-comparison or count rows where is_correct = 1 grouped by question id.

A few gotchas seen in the thread: do not call count() on a scalar or feed its result to mysql_fetch_array() — that expects a DB resource. Use $_SESSION (all caps) for PHP sessions. Avoid the old mysql_* extension; use mysqli or PDO with prepared statements. Finally, store answers as numeric types and either cast booleans to (int) in PHP or use SQL aggregation to get accurate counts directly from the database.

Recommended Answers

All 4 Replies

Member Avatar for Member #120589
SELECT `QuestionId`, `Que_Answer1` + `Que_Answer2` + `Que_Answer3` + `Que_Answer4` + `Que_Answer5` AS Num_Answers FROM table ORDER BY `QuestionId`

it prints 00110. Now will I be able to just have the 1 and add them and print this.

Member Avatar for Member #120589

What's the datatype? Should be tinyint.

yes it is

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.