Solved

Dynamic Select box array with 2 values

Posted on 2010-08-30
12
214 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 3
12 Comments
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 33560843
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 110

Expert Comment

by:Ray Paseur
ID: 33561155
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 31

Expert Comment

by:Marco Gasi
ID: 33561315
I'm sorry, link was correct: it's my router that is going bad! As usual, Ray says well: I go...
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:dsg138
ID: 33561373
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 31

Expert Comment

by:Marco Gasi
ID: 33561503
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 110

Expert Comment

by:Ray Paseur
ID: 33561583
"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
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 33561618
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
ID: 33563457
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 110

Expert Comment

by:Ray Paseur
ID: 33565513
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 110

Expert Comment

by:Ray Paseur
ID: 33565649
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 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 33566108
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
ID: 33573273
Ray, this is absolutely great.  What a much better way to do this.
As always, you've been a big help.
0

Featured Post

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
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 create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

740 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