Need help with changing default option selection

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lshaw
Forum Commoner
Posts: 69
Joined: Mon Apr 20, 2009 3:40 pm
Location: United Kingdom

Need help with changing default option selection

Post by lshaw »

Hello, I have recently being coding a sailing results, and I have a page where you can select a series and all the races from this series come up.
This is what selects the list of series:

Code: Select all

$query=mysql_query("SELECT * FROM series") or die(mysql_error());
while($array=mysql_fetch_array($query))
{
  echo("
  <option>$array[name]</option>
  ") ;
}
this is what selects the year:

Code: Select all

$query=mysql_query("SELECT * FROM series_years") or die(mysql_error());
while($array=mysql_fetch_array($query))
{
  echo("
  <option>$array[year]</option>
  ") ;
}
This then post two variables, series and year. Any races from this series and year are then fetched from the database. At the moment, the selected option is not the same as the one th user is viewing. For example, the user might be looking at Autumn 2009, when the selection boxes say Summer 2008. Is there anyway of keeping the default selected option the same as what the user is viewing?
Last edited by lshaw on Tue Jan 26, 2010 12:03 pm, edited 1 time in total.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Need help with changing default option selection

Post by AbraCadaver »

I'm assuming you are posting to a page which is showing these options again? If so, then this depends upon what you set the name of the select to (I will assume year), then something like this:

Code: Select all

$chosen_year = "";
if(isset($_POST['year'])) {
    $chosen_year = $_POST['year'];
}
while($array = mysql_fetch_array($query))
{
  $selected = "";
  if($array['year'] == $chosen_year) {
      $selected = " selected";
  }
  echo("<option{$selected}>" . $array['year'] . "</option>") ;
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
lshaw
Forum Commoner
Posts: 69
Joined: Mon Apr 20, 2009 3:40 pm
Location: United Kingdom

Re: Need help with changing default option selection

Post by lshaw »

Thank you so much! :D :D . This sort of code is used alot in this project and I have been leaving it for days, but now i finally have a solution :D

Thanks again,

Lewis
Post Reply