Re: Tough Select List with multiple arrays
| From: | Rasmus Lerdorf | Date: | Wed, 18 Oct 2000 23:46:35 +0000 |
| Subject: | Re: Tough Select List with multiple arrays | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-21012@lists.php.net to get a copy of this message | ||
> I have this SQL query and array.
> //Query to get the records of what games the player owns
> $game_query = mysql_query("SELECT game_id FROM games,members_games WHERE
> games.gameid=members_games.game_id AND member_id=$member_id GROUP BY
> game_id",$db);
> $game_result = mysql_fetch_array($game_query);
>
> So now I have a game_result array with numeric values in it.
Well, not really. $game_result just has one row of the result set. You
need to loop through to actually create the array using:
while($game_result = mysql_fetch_row($game_query)) {
$my_games[$game_result[0]] = 1; // Perhaps pull out the game title
// and use that here instead of just
// a '1'. You'll see why I used '1'
// further down
}
instead of that fetch_array call you did.
> Then I have this form for a member to update their information. It has a
> list of all game titles.
>
> $query1 = "SELECT * FROM games";
> $game_query = mysql_query($query1);
> while($games = mysql_fetch_array($game_query))
> {
> /* Get the game titles and gameids for the check box list menu */
> $game_title = $games["title"];
> $gameid = $games["gameid"];
>
> /* Output a drop down menu list of all the games that The Grognards
> supports from the games table. */
> print("<INPUT TYPE=\"checkbox\" NAME=\"games[]\"
> VALUE=\"$gameid\">$game_title<BR>\n");
> }
>
> What I want to be able to add a bit of code to the second part so that
> if($game_result == "$gameid") { echo "checked"; }
> This way in the full list of games is a member has already listed that
> they have the game is automatically selected.
> Then the member can add or delete game titles from his profile.
>
> How do I do this?
So you basically have 2 arrays and you want to find the intersection of
these two arrays and output "CHECKED" for elements that match.
In place of that second loop to print things out, just loop and create
your array of available games:
while($games = mysql_fetch_array($game_query,MYSQL_ASSOC)) {
$all_games[$games['title']] = $games['gameid'];
}
Presumably all games associated with a user will be present in the array
of all games, so your display loop is now just:
foreach($all_games as $title=>$gameid) { // (*)
echo '<INPUT TYPE="checkbox" NAME="games[]"
VALUE="'.$gameid.'" ';
if(isset($my_games[$gameid])) echo "CHECKED"; // (**)
echo ">$title<BR>\n";
}
(*) For PHP 3 use: while(list($title,$gameid)=each($all_games)) {
(**) Here you can see why I set $my_games to '1' previously. By creating
a hash where the game id is the hash you get an instant lookup to see
if that element is set.
-Rasmus