I’m trying to use mysql and php to show students their scores. The form page has 2 text input fields: class name, like 19BE1 and student number, a 10 digit number.
The code below does what I want, as long as the class and student number are correct. If there is a problem connecting with mysql, the catch (PDOException $e) will send an error message. I put a link in the error page back to the form.
For example, there is no class 19BE4, and therefore no mysql table 19BE4. If I write 19BE4, I get a catch (PDOException $e) error.
However, if I enter a wrong student number, I end up back at my formpage. Not quite sure how that happens! I would like an error message and a link to the formpage, or an error message in the formpage (form.html.php).
I’ve tried various things, but I haven’t succeeded yet. Any tips on how to get a nice error message if the student number is wrong please?
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/includes/magicquotes.inc.php';
include $_SERVER['DOCUMENT_ROOT'] . '/includes/studentdbReadfrom.inc.php';
if (isset($_POST['getclass'])){
try
{
$class = $_POST['getclass'];
$studentnum = $_POST['studentnum'];
$sql = 'SELECT number, name, score FROM ' . $class . 'scores WHERE number = ' . $studentnum . ';' ;
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching student data: ' . $e->getMessage();
include 'error.html.php';
exit();
}
}
if(isset($_POST['studentnum'])) {
foreach ($result as $row)
{
$numname[] = array(
'number' => $row['number'],
'name' => $row['name'],
'score' => $row['score'],
);
echo '$row[\'number\'] is ' . $row['number'] ;
echo '<br>';
echo '$row[\'name\'] is ' . $row['name'] ;
echo '<br>';
echo '$row[\'score\'] is ' . $row['score'] ;
echo '<br>';
include 'output.html.php';
exit();
}
}
include 'form.html.php';
?>