Do not use the ereg family of regex functions as they are (or will be) deprecated. In this case I might use strlen() and ctype_digit(), e.g.,
if (isset($_POST['serial'])) {
$serial_num = $_POST['serial'];
// Check for valid serial number entry.
if (strlen($serial_num) == 5 && ctype_digit($serial_num)) {
// Connect to and query DB and display results.
} else {
// Display invalid input error.
}
} else {
// Display missing input error, or the form.
}
If you want to use regex, use the PCRE family of regex functions, e.g.,
if (isset($_POST['serial'])) {
$serial_num = $_POST['serial'];
// Check for valid serial number entry.
if (preg_match('/^\d{5}$/', $serial_num)) {
// Connect to and query DB and display results.
} else {
// Display invalid input error.
}
} else {
// Display missing input error, or the form.
}
That said, the problem was that you were matching for 5 consecutive digits. Since within 6 consecutive digits there are 5 consecutive digits, there was a match for 6 consecutive digits. My regex pattern matches 5 consecutive digits from start to end, and that makes the difference.