views:

164

answers:

4

I have a simple html form. On php page. A simple list is placed on form. I submit this form (selected list items) to this page so it gives me page refresh. I want items which were POSTED to be selected after form was submited.

For my form I use such code, And It works just fine, But is it optimal or you can suggest some optimization for my code?

<form action="FormPage.php" method="post">
   <select id="Streams" class="multiselect ui-widget-content ui-corner-all" multiple="multiple" name="Streams[]">
     <?php      
     $query = "
SELECT s.streamId, s.userId, u.username
FROM streams AS s
JOIN user AS u ON s.userId = u.id
LIMIT 0 , 30
  ";
$streams_set = mysql_query($query, $connection);
    confirm_query($streams_set);    
    $streams_count = mysql_num_rows($streams_set);

while ($row = mysql_fetch_array($streams_set)){


      if (isset($_POST['submitForm'])){

      $array =  $_POST[Streams];
$count = count($array);
echo ",sid=" ;
for ($i = 0; $i < $count; $i++) {
 if($array[$i] == $row['streamId']){  echo '<option value="' , $row['streamId'] , '" selected="selected" >  ' , $row['username'] , ' (' , $row['streamId'] ,')' ,'</option> ';    }else
     {  echo '<option value="' , $row['streamId'] , '">  ' , $row['username'] , ' (' , $row['streamId'] ,')' ,'</option> ';  }
 }
} else { echo '<option value="' , $row['streamId'] , '">  ' , $row['username'] , ' (' , $row['streamId'] ,')' ,'</option> ';}

}
      </select>
      <br/>
      <input type="submit" class="ui-state-default ui-corner-all" name="submitForm" id="submitForm"  value="Play Stream from selected URL's!"/>    
  </fieldset>
</form>
+4  A: 

When you receive the POST, you'll need to update the database correctly and set the selected attribute on the <option> elements. For example:

$streams = $_POST['Streams'];
$selected = array_combine($streams, array_fill(0, count($streams), true);
$query = <<<END
SELECT s.streamId, s.userId, u.username
FROM streams AS s
JOIN user AS u ON s.userId = u.id
LIMIT 0 , 30
END;
$streams_set = mysql_query($query, $connection);
confirm_query($streams_set);    
$streams_count = mysql_num_rows($streams_set);
while ($row = mysql_fetch_array($streams_set)) {
  $id = $row['streamId'];
  $sel = $selected[$id] ? ' selected' : '';
  echo '<option value="' , $row['streamId'] , '"' . $sel . '>  ' , $row['username'] , ' (' , $row['streamId'] ,')' ,'</option> ';
}

That being said, this isn't considered best practice because it can inadvertently submit the form if the user uses the back button on their browser. For this reason many people prefer to use the POST+REDIRECT+GET pattern.

In your case the script will see that it's a POST and save the data to the database. It'll then send an HTTP redirect back to the user to reload the page or load a different URL (as required). That GET request will have the saved information. This results in an extra server round trip but typically a better user experience.

cletus
just a note - not sure if only in xhtml, but instead of `selected`, you should use `selected="selected"`
Adam Kiss
@Adam `selected` is valid HTML. You can specify `selected="selected"` if you wish. The HTML spec implies it http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.6
cletus
@Adam Kiss: that is only for xhtml. HTML5 doesn't require attribute/value pairs for boolean attributes.
Andy E
Thank you for specifying :]
Adam Kiss
hmm It just gives me an error on $selected = array_combine($streams, array_fill(0, count($streams), true); line (even if I put $query request into ""... )
Blender
A: 

Choice 1. Remove refresh and implement form submit using AJAX

Choice 2. Send back the post parameters to the form when it reloads as URL parameters/ or some other variable passing mechanish using sessions and show them in the form by getting the values from URL/session if the page is getting reloaded.

Umesh
Choice 1 isn't really an option if you want to support users with no JS.
Andy E
@Andy : I agree
Umesh
+1  A: 
<form action="FormPage.php" method="post">
   <select id="Streams" class="multiselect ui-widget-content ui-corner-all" multiple="multiple" name="Streams[]">
     <?php      
     $query = "
SELECT s.streamId, s.userId, u.username
FROM streams AS s
JOIN user AS u ON s.userId = u.id
LIMIT 0 , 30
  ";
$streams_set = mysql_query($query, $connection);
    confirm_query($streams_set);    
    $streams_count = mysql_num_rows($streams_set);

while ($row = mysql_fetch_array($streams_set)){
 echo '<option value="' . $row['streamId'] . '"' . (in_array($row['streamId'], $_POST['Streams']) ? ' selected' : ''). '>  ' . $row['username'] . ' (' . $row['streamId'] .')' .'</option> ';
} ?>
      </select>
      <br/>
      <input type="submit" class="ui-state-default ui-corner-all" name="submitForm" id="submitForm"  value="Play Stream from selected URL's!"/>    
  </fieldset>
</form>
vooD
It Works but saves only 1 selected item...(
Blender
Sorry, i didn't see that it is multiselect. Fixed.
vooD
A: 

first of all the name of select field must be "Streams[]" not "Streams". Or you won't get multiple choices. Also, your code looks too spaghetty for me. I suggest you to divide it into 2 parts: business logic and presentation logic.
First, we get all data:

<?php      
$query = "
SELECT s.streamId, s.userId, u.username
FROM streams AS s
JOIN user AS u ON s.userId = u.id
LIMIT 0 , 30
";
$streams_set = mysql_query($query, $connection);
confirm_query($streams_set);    
$streams_count = mysql_num_rows($streams_set);

while ($row = mysql_fetch_array($streams_set)){
  if (in_array($row['streamId'], $_POST['Streams'])) {
    $row['sel'] = 1; 
  } else {
    $row['sel'] = 0;
  }
  $select1[]=$row;
}

Then, make it output

<form action="FormPage.php" method="post">
   <select id="Streams" class="multiselect ui-widget-content ui-corner-all" multiple="multiple" name="Streams[]">
   <? foreach ($select1 as $row): ?>
     <option value="<?=$row['streamId']?>" <?if($row['sel'])?>selected<?endif?> >
       <?=$row['username']?> ( <?=$row['streamId']?> )
     </option>
   <? endforeach ?>
   </select>
      <br/>
      <input type="submit" class="ui-state-default ui-corner-all" name="submitForm" id="submitForm"  value="Play Stream from selected URL's!"/>    
  </fieldset>
</form>

Looks neat, isn't it?

Col. Shrapnel
Hmm it gives me "Parse error: syntax error, unexpected T_ELSE" in $row['sel'] = 1; else $row['sel'] = 0;
Blender
@Ole, yeah, it was written on-site, without a single run. corrected this one.
Col. Shrapnel
It runs with no errors now but... I get 5 "Warning: in_array() expects parameter 2 to be array, null given" in "if (in_array($row['streamId'], $_POST['Streams'])) {" And so I get no Items in form but one " <option value="<?=$row['streamId']?>" >selected > ( ) </option> "
Blender
Why not to learn PHP a bit?
Col. Shrapnel