Hi,

Ive been at this all weekend and can't figure it out.... I need to take it name and 3 results via a form and store this in a mysql database - done. Then I need to print on screen via php who got the highest score. The highest score is got by adding the 3 results together and the biggest sum of the 3 is the highest. I dont know how to do this.... code below is an idea of what i was trying to do but it wont work.. any help appreciated :)

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'exam';

mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to database');

mysql_select_db("$dbname") or die ("unable to conect to database");

$table = 'details';
$fname = $_POST['fname'];
$surname = $_POST['surname'];
$student_number = $_POST['student_number'];
$exam = $_POST['exam'];
$project = $_POST['project'];
$participation = $_POST['participation'];
$Totalmark = $exam + $project + $participation; 

$sqlquery = "INSERT INTO details VALUES ('$fname', '$surname', '$student_number', '$exam', '$project', '$participation', '$Totalmark')";
$results = mysql_query($sqlquery);

?>
<?php // code to get final grades
//$sqlquery2 = "SELECT max($Totalmark) $fname, $surname FROM details"; 
//$results2 = mysql_query($sqlquery2);

?>
	

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Exam Results</title>
</head>


<body>

<center><h1> Exam Results </h1></center>
<?php
while($row = mysql_fetch_array($results2))
{
?>

<?php
echo $Totalmark ['Totalmark'] ///plus name etc
?>
<?php
}
?>
</body>
</html>

Dani AI

Generated

A concise, practical fix and some modern best practices for 's task.

The immediate bugs in the original post are: SQL is being given PHP variables (for example max($Totalmark) — SQL needs column names or expressions), the result-set variable used in the loop ($results2) is never actually created, and the code prints $Totalmark['Totalmark'] which mixes a scalar PHP variable and an array syntax. correctly noticed a syntax issue; 's ORDER BY + LIMIT suggestion is the simplest when only a single winner is wanted; showed the nested-MAX approach which is useful when multiple rows can tie for top score.

Recommended approach (safe and maintainable)

  • Validate and cast incoming marks to numbers before using them.
  • Use prepared statements (PDO or mysqli) instead of the old mysql_* API.
  • Either compute the total when inserting and store it, or compute it on read. Computing on read avoids redundant data; storing avoids recalculating if reads are heavy.
  • To get a single top scorer use ORDER BY total DESC LIMIT 1. To return all ties use a ranking/window function (MySQL 8+) or compare against MAX(total).

Example (safe PDO insert + single-winner read):

$pdo = new PDO('mysql:host=localhost;dbname=exam;charset=utf8mb4','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$exam = (int)$_POST['exam'];
$project = (int)$_POST['project'];
$participation = (int)$_POST['participation'];

$ins = $pdo->prepare(
  'INSERT INTO details (fname,surname,student_number,exam,project,participation,totalmark)
   VALUES (:f,:s,:sn,:e,:p,:pa,:t)'
);
$ins->execute([
  ':f'=>trim($_POST['fname']), ':s'=>trim($_POST['surname']), ':sn'=>$_POST['student_number'],
  ':e'=>$exam, ':p'=>$project, ':pa'=>$participation, ':t'=>$exam+$project+$participation
]);

Read top scorer (compute total in SQL):

$winner = $pdo->query(
  'SELECT fname, surname, (exam+project+participation) AS total
   FROM details
   ORDER BY total DESC
   LIMIT 1'
)->fetch(PDO::FETCH_ASSOC);

Quick troubleshooting checklist

  • Confirm column names exactly match your table (case/typo issues).
  • Check SQL errors or PDO exceptions rather than suppressing them.
  • When iterating results, read from $row[...], not from the scalar $Totalmark.
  • Use the ORDER BY + LIMIT method for a single winner; use RANK()/window functions or compare against MAX(...) if ties must all be returned.

Recommended Answers

All 5 Replies

How you get $_POST variable on this page ?

How you get $_POST variable on this page ?

The post values are coming from a form I created where the user enters in the values....

That shouldn't be too difficult. One way you could do it (there will be better ways).

SELECT fname, $surname FROM details ORDER BY totalmark DESC LIMIT 1

So you're selecting the info you want (I don't know what your table headers are) from your database.

You're ordering it by total mark, descending (so highest first), and you're only taking one (limit 1).

$row = mysql_fetch_assoc($query);
$name = $row['firstname']. ' ' .$row['lastname'];
echo $name;

The code that you're using should work,

<?php // code to get final grades
//$sqlquery2 = "SELECT max($Totalmark) $fname, $surname FROM details";
//$results2 = mysql_query($sqlquery2);

If you inserted the missing comma between max($Totalmark) and $fname.
Might be worth a try.

Member Avatar for Member #334542

Sample Table:

CREATE TABLE `highestScore` ( 
    `id` int(11) NOT NULL auto_increment, 
    `fname` varchar(255) NOT NULL default '', 
    `lname` varchar(255) NOT NULL default '', 
    `TotalMarks` int(11)NOT NULL default '', 
    PRIMARY KEY  (`id`) 
) TYPE=MyISAM;

Sample Datas:

INSERT INTO `highestscore` VALUES (1, 'Raja', 'Rajan',100);
INSERT INTO `highestscore` VALUES (2, 'Vino', 'Thini',55);
INSERT INTO `highestscore` VALUES (3, 'Rajendra', 'Kumar',150);
INSERT INTO `highestscore` VALUES (4, 'Senthil', 'Kumar',125);
INSERT INTO `highestscore` VALUES (1, 'John', 'Kamer',150);

Note that I have code more than one maximum value

<html> 
<head> 
<basefont face="Arial"> 
</head> 
<body> 

<?php 
$host = "localhost"; 
$user = "root"; 
$pass = ""; 
$db = "testdb"; 

$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); 
mysql_select_db($db) or die ("Unable to select database!"); 
$query = "select * from highestscore where totalmarks=(select max(totalmarks) from highestScore)";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 
if (mysql_num_rows($result) > 0) { 
    echo "<table cellpadding=10 border=1>"; 
	echo "<tr align='center'><td colspan='3'>HighestScore</td></tr>";
    while($row = mysql_fetch_row($result)) { 
        echo "<tr>"; 
        echo "<td>".$row[1]."</td>"; 
        echo "<td>" . $row[2]."</td>"; 
        echo "<td>".$row[3]."</td>"; 
        echo "</tr>"; 
    } 
    echo "</table>"; 
} 
else { 
    echo "No rows found!"; 
} 
mysql_free_result($result); 
mysql_close($connection); 
?> 
</body> 
</html>

This will give you the good viewable output in a table. If a person have a highest score then It display a single record. if maximum marks achieved by two person. This will work at that scenario too.

SELECT fname, $surname FROM details ORDER BY totalmark DESC LIMIT 1SELECT fname, $surname FROM details ORDER BY totalmark DESC LIMIT 1

The above code will not work if you have more than one record

<?php // code to get final grades//$sqlquery2 = "SELECT max($Totalmark) $fname, $surname FROM details"; //$results2 = mysql_query($sqlquery2); ?>

The above code will not work because it only returns the maximum mark and the details of the person will be a first record. Thats wrong!

Hope this solve! COOL!

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.