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>

Link to comment
Share on other sites

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 . . .

Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.