Juddling
Juddling

Reputation: 4690

Logical order of PHP queries

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?

Upvotes: 0

Views: 331

Answers (2)

netcoder
netcoder

Reputation: 67695

I would have done it in a single query:

$query = mysql_query("SELECT * FROM bodyguards WHERE username='$u' OR (bodyguard='$u' AND (status='active' OR status='invited')");

$bg = mysql_fetch_assoc($query);

if ($bg) { // check for empty result first, to prevent E_NOTICE
    if ($bg['username'] == $u) {
        if($bg['status'] == "active") {
            echo "your bodyguard is {$bg['bodyguard']}, kick him?";
        } else {
            echo "invite a bg?";
        }
    } else if ($bg['bodyguard'] == $u) {
        if ($bg['status'] == "active") {
            echo "you are the bodyguard of {$bg['username']}";
        } else if ($bg['status'] == "invited") {
            echo "{$bg['username']} has invited you to be their bodyguard, accept or decline?";
        }
    }
}

NOTE: Make sure you are escaping $u if the data is supplied by a user, using mysql_real_escape_string. Also, make sure you quote your array indices to prevent PHP notices (i.e.: use $bg['username'] instead of $bg[username]).

Upvotes: 3

Dutchie432
Dutchie432

Reputation: 29160

Whenever I have a releationship between two entities in a table, I usually make another table to hold the relationship.

My BodyGuardRelations table might look like

[id] [userId] [bodyGuardUserId] [status]
1    27       55                Active
2    43       89                Invited

Upvotes: 0

Related Questions