Jump to content

Set Selectbox index as post on submit with php


Recommended Posts

I'm trying to set the select to whatever was posted. In this case I'm using dates.

 

I think I may have my loops wrong. On every post I get the select set to the first date in my date array ($options)

 

I've tried putting the loops in different places but can't get it right. 

 

Any help is appreciated.

<?php
//Getting the Dates
    $date_query="Select Game_Date from june122011 GROUP BY Game_Date DESC";
$date_results=mysql_query($date_query); 
$options="";
//setting the select as post
$x="";
// check if Post Select is set and set x to post
if (isset($_POST['Select']) AND strlen($_POST['Select']>0)) {
	$x=$_POST['Select'];
}
//loop through dates	
while ($row=mysql_fetch_array($date_results)) {
$thedays=$row["Game_Date"];
//if date = the post set it as selected
if ($x==$thedays) {
		$x='selected="selected"';
	} 
    $options.="<OPTION VALUE=\"$thedays\" $x>".$thedays.'</option>';
}
// end getting dates ?>

 

Then the html part:

<select name="Select" id="Select" class="select">
      <?php echo $options ?>
    </select>

Comment out this for the moment:

if ($x==$thedays) {
		$x='selected="selected"';

 

And put this in it's place:

$x = ( !empty($_POST['Select']) && $_POST['Select'] == $thedays ) ? 'selected="selected"' : '';

 

Should work, unless I've misread something . . .

That certainly did fix it. Thank you very much for that.

 

I don't want to impose but I'm learning PHP as I go, mostly I just keep trying stuff till it works. :)

 

Can you explain what your code is doing there at the end?

 

I understand the first part just checking if not empty and the values match, but the end part with the ? and : I'm not familiar with sort of functionality.

 

 

That's called ternary syntax, it's basically an abbreviated if/else conditional. It does the same as:

if( !empty($_POST['Select']) && $_POST['Select'] == $thedays ) {
     $x = 'selected="selected"';
} else {
     $x = '';

 

See example #2 and #3 HERE for more info.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.