Hi all!
I'm trying to learn php and am struggling with validation. I'm not sure whether it's best to use php or javascript, but I thought I'd try using php given I'm trying to learn the language 🙂
Can you help me with the following problem I have?
I have a list of surnames read from a database and displayed in an html table using this loop:
while($row = db2_fetch_assoc($numresults))
{
if (is_int($count/2)) {
echo '<tr class="even">'."\n";
} else {
echo '<tr class="odd">'."\n";
}
echo '<td><input style="width:300px;" name="surname[]" value="' . trim($row['SURNAME']) . '" type="text"
maxlength="30"><input type="hidden" name="rrn[]" value="' . $row['RRN'] . '"></td>'."\n";
echo '</tr>'."\n";
$count ++;
}
The hidden RRN field is a unique key to the database record.
When the user makes changes and hits submit I validate and update using this loop:
if ($_POST['update'] == 'Update') {
foreach (array_keys($_POST['rrn']) as $key => $val) {
$surname = $_POST['surname'][$key];
/* Name cannot be blank */
if($surname == ''){
array_push($message, 'Name cannot be blank');
}
}
/* Display error */
if(!empty($message)){
echo '<div class="messageStackError">';
foreach($message as $value){
echo '<img src="/images/error.gif" alt="Error" title="Error" width="20" height="20" />';
echo $value;
echo '<br />';
}
echo '</div>';
echo '<br />';
}
/* Update if no errors */
if (empty($message)) {
/* UPDATE THE DATABASE */
}
}
When the user updates one of the surnames and hits the 'Update' button, the form submits itself.
It goes through the validation loop and displays any error messages, then redisplays the form.
This all works great, but I'm wondering if there's a way to highlight the particular name in the list that is in error rather than just display the error message in the messageStackError <div> as I am doing.
The other problem I have with my approach is because the form redisplays each time, any invalid entries disappear because the data is being read back from the database.
Is it good practice to do what I'm trying or should I be using javascript to validate?
Thanks for your help!
Regards,
Damian