Solved

Dynamic Select box array with 2 values

Posted on 2010-08-30
12
202 Views
Last Modified: 2013-12-13
Experts,
I have a list of games/matches where I want my users to choose a winner.
They make their choices via Select Boxes.  Each week the winner will choose many games.

When the user clicks the Submit button, I need the following to happen:
Each game that the user picks is entered into the PICKS table:
-  UserID
-  WeekID
-  GameID
-  CHOICE

The UserID and WeekID are already known from the users login.

Each checkbox needs to add GameID and CHOICE to the PICKS table.

Here is the sample page:
http://www.officepickem.com/ncaa/weeklypicks.php

So in the first Select Box, User #300, for Week #1, selects "Utah" in GameID #4.

The 2 things I'm having trouble with are:
1.  Passing BOTH the GameID and the CHOICE from the select box.
2.  Making the array so it inserts 12 records to the DB and not just 1.

I'm sure others have done something like this before, but I'm just unsure of how to setup the <FORM> and the SELECT Array.

If Possible, I'd like the form to UPDATE as well, so if a user comes back later, they can CHANGE their pick.

Thanks in advance,

-Dan
0
Comment
Question by:dsg138
  • 5
  • 4
  • 3
12 Comments
 
LVL 30

Expert Comment

by:Marco Gasi
Comment Utility
Sorry, but something goes wrong with the link you have provided and Firefox doesn't load the page. Please chek link for errors. But, as I'm here, I don't understand if you are talking about some checkboxes or a select: can you be more clear?

Tahnks
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
You have a lot of constructs that all look the same, like this:

<select name="TeamChoice" id="TeamID" style="width: 150px;">
      <option selected></option>
      <option>
      Arizona U      </option>
      <option>
      Toledo      </option>
    </select>

What you need is to differentiate the "TeamChoice" name so that it includes the key of the game.  You can make this an array or just append an underscore and the numeric key of the game.

You might want to get some foundation in PHP and MySQL.  This book can help.
http://www.sitepoint.com/books/phpmysql4/

Good luck with it, ~Ray
0
 
LVL 30

Expert Comment

by:Marco Gasi
Comment Utility
I'm sorry, link was correct: it's my router that is going bad! As usual, Ray says well: I go...
0
 

Author Comment

by:dsg138
Comment Utility
Marqus, sorry, didn't mean to say Check boxes.  By Select boxes, I mean Drop down boxes or Combo boxes.  

Thanks Ray...
This is actually in PHP, the select (Drop Down Box) is in a while loop that goes through the entire schedule of games.

<select name="TeamChoice" id="TeamID" style="width: 150px;">
      <option selected></option>
      <option>
      $[a1]Underdog      </option>
      <option>
      $[a1]$Favorite      </option>
    </select>

If I added TeamChoice to the Game ID, my users would see something like this:  
LSU_28
North Carolina_28

I'd like to avoid that if possible since it'll probably confuse them.

Is there a way I can pass 2 variables with the Combo Box.
-  The Choice
-  The GameID (which is hidden)
0
 
LVL 30

Expert Comment

by:Marco Gasi
Comment Utility
Each html element has a name and a value, so you can use GameID as option name and The Choice as option value:
user see only MNorth Carolina, but you can process option name also, that is 28.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
"If I added TeamChoice to the Game ID, my users would see something like this:  LSU_28 North Carolina_28"

Nope.  It's an HTML thing.  Try something more like this.
<option selected>CHOOSE</option>
<option value="$[a1]$Underdog">$Underdog</option>
<option value="$[a1]$Favorite">$Favorite</option>
</select>

Open in new window

0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 30

Expert Comment

by:Marco Gasi
Comment Utility
Ah, ah, ah! That is what I wont to say, Ray, but I made a bit of confusion... Good bye
0
 

Author Comment

by:dsg138
Comment Utility
Thanks Ray,
Below is the code sample and here is the updated link:
http://www.officepickem.com/ncaa/weeklypicks.php

I added both values to the SELECT variable.

I'm unsure of the following:
1.  My syntax for the values in the Select Statement
2.  How to pull those out in my if(isset($_POST['Submit']) so I can add them.
3.  How to turn this into an Array so the user is adding 12 values to the database when clicking Submit.

i really appreciate your help.  You've helped me on a few projects before.  
Thanks in advance,
-Dan
//For testing purposes, using UserID:  300.



if(isset($_POST['Submit']) && $_POST['Submit'] == "Submit") 

{

$finalPID = $_POST["teamid"];

$finalselection = $_POST["selection"];



$sql = "INSERT INTO PICKS SET 

	userid = '300',

	weeknum = '1',

	GamePID = '$finalPID',

	CHOICE = '$finalselection'"

	;

$sql = mysql_query($sql);



?>

<script type="text/javascript">

document.location.href = "test.php";

</script>

<?

}



?>



<FORM name="Rounds" method="post" action="<?php echo $_SERVER['../../PHP_SELF']; ?>">

  <p>

    <strong>Choose the Favorite/Underdog for these selected 10 games:</strong>

    <?



echo "<TABLE WIDTH =750 BORDER=2 align=center>";

echo "<TR>";

echo "<TD WIDTH = 25>" . "Game #";

echo "<TD WIDTH = 25>" . "Game PID";

echo "<TD WIDTH = 145>" . "Day/Time";

echo "<TD WIDTH = 240>" . "FAVORITE";

echo "<TD WIDTH = 240>" . "SPREAD";

echo "<TD WIDTH = 25>" . "UNDERDOG";

echo "<TD WIDTH = 25>" . "PLAYED AT";

//echo "<TD WIDTH = 25>" . "Selection";

echo "<TD colspan =2 WIDTH = 25>" . "Make a selection:";

echo "</TR>";



$gamenum = 1;



	$q1="select * from WeeklyGames where WeekNum = '1' AND Selection ='Top10' order by PID asc";

	$r1=mysql_query($q1) or die(mysql_error());

	while ($a1=mysql_fetch_array($r1)) {

		echo "<TR>";

		echo "<TD>" . $gamenum . "</TD>";

		echo "<TD>" . $a1[PID] . "</TD>";

		echo "<TD>" . date("D, h:i A",strtotime($a1[GMTDate]) -3600 *4 ). "</TD>";

		echo "<TD>" . $a1[FAV] . "</TD>";

		echo "<TD>" . $a1[SPREAD] . "</TD>";

		echo "<TD>" . $a1[UDOG] . "</TD>";

		echo "<TD>" . $a1[HomeTeam] . "</TD>";

		$gamenum = $gamenum+1;

		echo "<TD>";

		$teamnum = $a1[PID];

		$udog = $a1[UDOG];

		$fav = $a1[FAV];

?>		

    <select name="TeamChoice[]" id="TeamID" style="width: 150px;">

      <option selected></option>

      <option value="<?=$teamnum$fav?>"><?=$fav?></option>

      <option value="<?=$teamnum$udog?>"><?=$udog?></option>

   </select>

    </TD>

    

    <?	

		

		;	}

	echo "<TD></TD>";

	echo "</TR>";

echo "</TABLE>";	

	



?>

  </p>

  <hr>

  <p><strong>Write Ins:  Choose the Favorite/Underdog for 2 of these games:</strong>

    <?



echo "<TABLE WIDTH =750 BORDER=2 align=center>";

echo "<TR>";

echo "<TD WIDTH = 25>" . "Game #";

echo "<TD WIDTH = 25>" . "Game PID";

echo "<TD WIDTH = 145>" . "Day/Time";

echo "<TD WIDTH = 240>" . "FAVORITE";

echo "<TD WIDTH = 240>" . "SPREAD";

echo "<TD WIDTH = 25>" . "UNDERDOG";

echo "<TD WIDTH = 25>" . "PLAYED AT";

//echo "<TD WIDTH = 25>" . "Selection";

echo "<TD colspan =2 WIDTH = 25>" . "Make a selection:";

echo "</TR>";



$gamenum = 1;



	$q2="select * from WeeklyGames where WeekNum = '1' AND Selection ='Write-In' order by PID asc";

	$r2=mysql_query($q2) or die(mysql_error());

	while ($a2=mysql_fetch_array($r2)) {

		echo "<TR>";

		echo "<TD>" . $gamenum . "</TD>";

		echo "<TD>" . $a2[PID] . "</TD>";

		echo "<TD>" . date("D, h:i A",strtotime($a2[GMTDate]) -3600 *4 ). "</TD>";

		echo "<TD>" . $a2[FAV] . "</TD>";

		echo "<TD>" . $a2[SPREAD] . "</TD>";

		echo "<TD>" . $a2[UDOG] . "</TD>";

		echo "<TD>" . $a2[HomeTeam] . "</TD>";

		$gamenum = $gamenum+1;

		echo "<TD>";

		$teamnum = $a2[PID];

		$udog = $a2[UDOG];

		$fav = $a2[FAV];

?>		

    <select name="TeamChoice2[]" id="TeamID" style="width: 150px;">

      <option selected></option>

       <option value="<?=$teamnum$fav?>"><?=$fav?></option>

      <option value="<?=$teamnum$udog?>"><?=$udog?></option>

   </select>

  </p>

  </TD>

	

	<?	

		;	}

		

	//echo "<TD></TD>";

	echo "</TR>";

echo "</TABLE>";	

?>

  <hr>

  <p><center>

<input type="Submit" name="Submit" value="Submit"></center></form>

  </p>

</BODY></HTML>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
I'll try to give you an example in a moment.  The PHP function var_dump() is your friend here.  If you echo "<pre>" before var_dump($_POST) it will be easy to read.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Here is a teaching example of how the dropdown / select control works.  You can install it and run it to see the moving parts.

That said, I think I would use radio buttons to make the selections of the teams.  I will look for a good example of that design pattern in a moment.
<?php // RAY_dropdown_select.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;


// SHOW HOW TO PRESENT AND PROCESS A DROPDOWN SELECT LIST
// MAN PAGE http://www.w3.org/TR/html401/interact/forms.html#h-17.6


// IF ANYTHING HAS BEEN POSTED IN THE SINGLE SELECT FORM
if (!empty($_POST["pick1"]))
{
    echo PHP_EOL . "YOU SELECTED {$_POST["pick1"]} FROM THE SINGLE DROPDOWN LIST";
    echo PHP_EOL . "HERE IS THE POST ARRAY: ";
    var_dump($_POST);
}


// IF ANYTHING HAS BEEN POSTED IN THE MULTIPLE SELECT FORM
if (!empty($_POST["pick2"]))
{
    // SHOW HOW TO FIND THE SELECTED ITEMS
    foreach ($_POST["pick2"] as $item)
    {
        // IGNORE EMPTY OPTION ITEMS
        if (empty($item)) continue;
        echo PHP_EOL . "YOU SELECTED {$item} FROM THE MULTIPLE DROPDOWN LIST";
    }
    echo PHP_EOL . "HERE IS THE POST ARRAY: ";
    var_dump($_POST);
}


// END OF PHP - DROP INTO HTML AND PUT UP THE FORMS
?>
<form method="post">
PLEASE CHOOSE ONE FROM THIS LIST
<select name="pick1">
<option value="" selected="selected">CHOOSE ONE</option>
<option value="value-abc">ABC</option>
<option value="value-def">DEF</option>
<option value="value-xyz">XYZ</option>
</select>
<input type="submit" />
</form>

<form method="post">
PLEASE CHOOSE ONE OR MORE FROM THIS LIST
<select multiple="multiple" name="pick2[]">
<option value="" selected="selected">CHOOSE ONE OR MORE</option>
<option value="value-abc">ABC</option>
<option value="value-def">DEF</option>
<option value="value-xyz">XYZ</option>
</select>
<input type="submit" />
</form>

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
Here is how you might use radio buttons to select the teams.  This might be a little easier on the clients than a dropdown.

The code through line 36 is test data generation.  This would come from your data base,

Line 38 - 68 generates the form in a tabular format.  You might try running this without line 61 to see the effect of an unselected radio button (nothing in POST).

Line 72 through 90 processes the form data.

Hope that helps, ~Ray
<?php // RAY_temp_dsg138.php
error_reporting(E_ALL);


// A CLASS TO REPRESENT THE CONTESTS
class Game
{
    // SOME VARIABLES - ID, FAVORITE, UNDERDOG
    protected $gid, $fav, $dog;

    // A CONSTRUCTOR TO LOAD THE VARIABLES
    public function __construct($g, $f, $d)
    {
        $this->gid = $g;
        $this->fav = $f;
        $this->dog = $d;
    }

    // GETTER METHODS TO RETREIVE THE VARIABLES
    public function getGid() { return $this->gid; }
    public function getFav() { return $this->fav; }
    public function getDog() { return $this->dog; }

} // END CLASS Game

// CREATE AN ARRAY OF GAME OBJECTS - IN REAL LIFE THIS WOULD COME FROM A DATA BASE QUERY
$games = array
( new Game( 1, 'Utah',     'Pittsburgh' )
, new Game( 2, 'Arizona',  'Toledo' )
, new Game( 3, 'Missouri', 'Illinois' )
, new Game(15, 'Syracuse', 'Akron' )
)
;
// ACTIVATE THIS TO LOOK AT THE ARRAY OF OBJECTS
// var_dump($games);


// CREATE A FORM WITH A TABLE OF GAMES
echo '<form method="post">' . PHP_EOL;
echo "<table><tr><td>ID</td><td>FAVORITE</td><td>UNDERDOG</td><td>PICK</td></tr>" . PHP_EOL;
foreach ($games as $game)
{
    // PRESENT A ROW FOR EACH OF THE CONTESTS
    echo "<tr>";
    echo "<td>";
    echo $game->getGid();
    echo "</td>";

    // THE FAVORITE
    echo "<td>";
    echo '<input type="radio" name="pick_' . $game->getGid() . '" value="' . $game->getFav() . '" />' . $game->getFav();
    echo "</td>";

    // THE UNDERTOAD
    echo "<td>";
    echo '<input type="radio" name="pick_' . $game->getGid() . '" value="' . $game->getDog() . '" />' . $game->getDog();
    echo "</td>";

    // THE UN-SELECTED
    echo "<td>";
    echo '<input type="radio" checked="checked" name="pick_' . $game->getGid() . '" value="' . 'NO PICK' . '" />' . 'NO PICK';
    echo "</td>";

    echo "</tr>" . PHP_EOL;
}
echo '</table>' . PHP_EOL;
echo '<input type="submit" />' . PHP_EOL;
echo '</form>' . PHP_EOL;



// THE ACTION SCRIPT -- SHOW HOW TO GET THE SELECTED TEAMS
if (!empty($_POST))
{
    foreach ($_POST as $key => $value)
    {
        // PROCESS EACH OF THE PICKS
        if (substr($key,0,5) == 'pick_')
        {
            // GET THE GAME NUMBER AND SELECTED WINNER
            $number = str_replace('pick_', '', $key);
            $winner = $value;

            // ESCAPE THE EXTERNAL DATA COMMENTED OUT FOR TESTING
            // $number = mysql_real_escape_string($number);
            // $winner = mysql_real_escape_string($winner);

            // SET UP A QUERY
            $sql = "UPDATE game_picks_table SET chosen_winner = '$winner' WHERE game_id = '$number' LIMIT 1";
            echo PHP_EOL . $sql . "<br/>";
        }
    }

    // ACTIVATE THIS TO SEE THE POST ARRAY
    // var_dump($_POST);
}

Open in new window

0
 

Author Comment

by:dsg138
Comment Utility
Ray, this is absolutely great.  What a much better way to do this.
As always, you've been a big help.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now