How to make data in mysql only selectable once via a webform?
I'm building a simple web form (or tying to!) which displays a list of football teams. This list of teams is located in a single column mysql table. How can I make it so that if a team has been selected on the web form, that it cannot be selected again on the form? i.e. to make sure they are not accidentally selected to play each other, or play twice at the same time. My code so far is as below, which seems to be working fine开发者_开发技巧. It includes several other iterations of the same code for the other home teams and away teams. Any pointers/help greatly appreciated.
<select name="hometeam">
<?php
$query = "SELECT * FROM teams order by teamname";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo "<option value=\"".$row['teamname']."\">".$row['teamname']."</option>\n ";
}
?>
</select>
<select name="hometeam2">
<?php
$query = "SELECT * FROM teams order by teamname";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo "<option value=\"".$row['teamname']."\">".$row['teamname']."</option>\n ";
}
?>
</select>
I Method: A possible and simple solution of this can be through javascript. That is, once the selection has been made at both the combo-boxes, then before submitting the form to the server, you can compare the two values and if they are found to be same then you can alert the user about this.
Also, just to add, though you validate using javascript, but its always advisable to re-validate at the server side to avoid any hack. Hope this helps.
II Method: If you don't want to show the team chosen in one drop-down in other drop-down then for this you will have to use Ajax in following manner:
On selection of a value in one drop-down - fire an ajax request - sending the chosen value from the dropdown to the server. Now, modify the query at the server to select all the values excluding this value and then send the values back to the client. This way the user will be able to see the values excluding the chosen one.
Hope this helps.
jQuery would make this quite simple:
<script type="text/javascript">
$(document).ready(function() {
$("select[name=hometeam]").change(function() {
if ( $(this).val() == $("select[name=hometeam2]").val() ) {
alert("This team cannot play itself!");
}
});
$("select[name=hometeam2]").change(function() {
if ( $(this).val() == $("select[name=hometeam]").val() ) {
alert("This team cannot play itself!");
}
});
});
</script>
http://jquery.com/
精彩评论