php - 如何在发布请求后保持选择表单项?

标签 php html list forms select

我有一个简单的 html 表单。在 php 页面上。表格上放置了一个简单的列表。我将此表单(选定的列表项)提交到此页面,以便它可以刷新页面。我希望在提交表单后选择已发布的项目。

对于我的表单,我使用这样的代码,它工作得很好,但是它是最佳的还是您可以建议对我的代码进行一些优化?

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

最佳答案

当您收到 POST 时,您需要正确更新数据库并设置 selected <option> 上的属性元素。例如:

$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> ';
}

话虽如此,这并不被认为是最佳实践,因为如果用户使用浏览器上的后退按钮,它可能会无意中提交表单。出于这个原因,很多人更喜欢使用 POST+REDIRECT+GET pattern .

在您的情况下,脚本将看到它是 POST 并将数据保存到数据库。然后,它会将 HTTP 重定向发送回用户以重新加载页面或加载不同的 URL(根据需要)。该 GET 请求将包含保存的信息。这会导致额外的服务器往返,但通常会带来更好的用户体验。

关于php - 如何在发布请求后保持选择表单项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2577997/

相关文章:

python - 关于 Python 中反向列表的问题

php - 自动更正 Web 应用程序中的拼写错误

html - 垂直居中 :after content in Bootstrap 3 panel-heading

javascript - ExpressJS 用于在 GET 请求上呈现内容

html - 如何删除 CSS line-through

java - 从 Elasticsearch 中获取索引名称匹配模式的列表 - JAVA

c++ - 由带节点的链表组成的类似 STL 的列表

php - 从 mysql 输出 blob

PHP计算一个字符串中的字符在另一个字符串中出现的次数

php - Laravel 5.3 - 避免在 phpunit 测试中发送松弛通知