I am using PHP to generate an HTML form for a ranking task, in order to obtain the rank order that the user assigns to a list of alternatives. The generated form is presented as a <table>
in which the rows containing the alternatives are randomised. The generated form HTML will be something like (for instance):
<table>
<tbody>
<tr>
<th align="Left">Action</th>
<th>Rank</th>
</tr>
<tr>
<td>
<input id="alt_ord_2" type="hidden" value="1" name="alt_ord[]">
<input id="alt_id2" type="hidden" value="2" name="alt_id[]">
Alternative 2 text
</td>
<td align="center">
<input id="rankid_[2]" type="text" size="1" maxlength="1" name="rank_[2]">
</td>
</tr>
<tr>
<td>
<input id="alt_ord_1" type="hidden" value="2" name="alt_ord[]">
<input id="alt_id1" type="hidden" value="1" name="alt_id[]">
Alternative 1 text
</td>
<td align="center">
<input id="rankid_[1]" type="text" size="1" maxlength="1" name="rank_[1]">
</td>
</tr>
<tr>
<td>
<input id="alt_ord_4" type="hidden" value="3" name="alt_ord[]">
<input id="alt_id4" type="hidden" value="4" name="alt_id[]">
Alternative 4 text
</td>
<td align="center">
<input id="rankid_[4]" type="text" size="1" maxlength="1" name="rank_[4]">
</td>
</tr>
<tr>
<td>
<input id="alt_ord_3" type="hidden" value="4" name="alt_ord[]">
<input id="alt_id3" type="hidden" value="3" name="alt_id[]">
Alternative 3 text
</td>
<td align="center">
<input id="rankid_[3]" type="text" size="1" maxlength="1" name="rank_[3]">
</td>
</tr>
</tbody>
</table>
So I'm trying to come up with a way to validate the user inputs using PHP, so that the four values entered = [1, 2, 3, 4]; i.e. all entered values are not empty, unique integers between 1 and 4 (the rank order). I am using $_POST
to submit the form.
I'm new to this, so any help would be greatly appreciated.
Edit: here is the PHP code used to generate the form.
$rand_ord = "SELECT * FROM altrank ORDER BY rand()";
$result = $link->query($rand_ord) or die(mysql_error($link));
if($result->num_rows > 0){
$ord = 0;
echo "<form action='".htmlspecialchars($_SERVER["PHP_SELF"])."' method='post'><table border='1'>
<tr><th align='Left'>Action</th><th>Rank</th>";
while ($row = $result->fetch_object()){
echo '<tr>';
echo '<td>
<input type="hidden" name="alt_ord[]" id="alt_ord_'.htmlspecialchars($row->id).'" value="'.++$ord.'">
<input type="hidden" name="alt_id[]" id="alt_id'.htmlspecialchars($row->id).'" value="'.htmlspecialchars($row->id).'">'.htmlspecialchars($row->alttext).'</td>';
echo '
<td align="center"><input type="text" name="rank_[]" id="rankid_['.htmlspecialchars($row->id).']" maxlength=1 size=1></td>';
echo '</tr>';
}
echo "</table><input type='submit' value='Submit' /></form>";
}
else {
echo "Error: ".$link->error;
}
$link->close();
I figured out a simple solution that compares the
$_POST
array against a pre-specified array of accepted values, based on this.The validation code:
Seems to work perfectly. Hope this helps others with the same problem.