I’ve just wrote some code for a basic outline of a page. It for a game I run, but looking at the code I feel I’ve written it in the wrong order, and that i’m executing more queries than I need to.
$query = mysql_query("SELECT * FROM bodyguards WHERE username='$u'");
if($bg = mysql_fetch_assoc($query)) { // if you have a bg
if($bg[status] == "active") {
echo "your bodyguard is $bg[bodyguard], kick him?";
} else {
echo "invite a bg?";
}
} else {
$query = mysql_query("SELECT * FROM bodyguards WHERE bodyguard='$u' AND status='active'");
if($bg = mysql_fetch_assoc($query)) { // if you are a bg
echo "you are the bodyguard of $bg[username]";
} else {
//otherwise check if anyone has invited you
$query = mysql_query("SELECT * FROM bodyguards WHERE bodyguard='$u' AND status='invited'");
while($temp = mysql_fetch_assoc($query)) {
echo "$temp[username] has invited you to be their bodyguard, accept or decline?";
}
}
}
i’m only using one database table. if a player1 had a confirmed bodyguard (player2) the row would look like:
username => player1,
bodyguard => player2,
status => active.
would anyone here have written the code in a different way?
I would have done it in a single query:
NOTE: Make sure you are escaping
$uif the data is supplied by a user, usingmysql_real_escape_string. Also, make sure you quote your array indices to prevent PHP notices (i.e.: use$bg['username']instead of$bg[username]).