drrvnbwle80177811 2014-11-29 00:05
浏览 47
已采纳

php中的下拉列表仅作为默认复选框

I am trying to convert my search page from using a checkbox styled method to being able to use a drop down box to select each separate title header as a potential search option. However when converting this the title drop down box still acts as its old checkbox style, being that it only shows the data that is stored within the title name no matter which title is selected.

PHP Section:

mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());

// Set up our error check and result check array
$error = array();
$results = array();

// First check if a form was submitted. 
// Since this is a search we will use $_GET
if (isset($_GET['search'])) {
$searchTerms = trim($_GET['search']);
$searchTerms = strip_tags($searchTerms); // remove any html/javascript.

if (strlen($searchTerms) < 3) {
  $error[] = "Search terms must be longer than 3 characters.";
}else {
  $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection.
}

// If there are no errors, lets get the search going.
if (count($error) < 1) {
  $searchSQL = "SELECT sid, sbody, stitle, sdescription FROM simple_search WHERE ";

  // grab the search types.
  $types = array();
  $types[] = isset($_GET['body'])?"`sbody` LIKE '%{$searchTermDB}%'":'';
  $types[] = isset($_GET['title'])?"`stitle` LIKE '%{$searchTermDB}%'":'';
  $types[] = isset($_GET['desc'])?"`sdescription` LIKE '%{$searchTermDB}%'":'';

  $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked)

  if (count($types) < 1) 
     $types[] = "`sbody` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked

      $andOr = isset($_GET['matchall'])?'AND':'OR';
  $searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `stitle`"; // order by title.

  $searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}");


  if (mysql_num_rows($searchResult) < 1) {
     $error[] = "The search term provided {$searchTerms} yielded no results.";
  }else {
     $results = array(); // the result array
     $i = 1;
     while ($row = mysql_fetch_assoc($searchResult)) {
        $results[] = "{$i}: {$row['stitle']}<br />{$row['sdescription']}<br />{$row['sbody']}<br /><br />";
        $i++;
     }
  }
}
}

function removeEmpty($var) {
return (!empty($var));

HTML Section:

<body>
  <?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?>
  <form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm">
     Search For: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /><br />
     Search In:<br />
     Body: <input type="checkbox" name="body" value="on" <?php echo isset($_GET['body'])?"checked":''; ?> /> | 
     Title: <form action="form_action.asp">
     <select name="title">
     <option value="Test Simple Search 1">Test Simple Search</option>
     <option value="Searching Made Easy 101">Search Made Easy</option>
     <option value="Gateway to Information">Gateway to Information</option>
     <option value="The Gaming World as we Know it">Gaming World</option>
     <option value="Hundreds of Ants Attacking">Ants Attacking</option>
     <?php echo isset($_GET['title'])?"checked":''; ?> </select> | 
     Description: <input type="checkbox" name="desc" value="on" <?php echo isset($_GET['desc'])?"checked":''; ?> /><br />
             Match All Selected Fields? <input type="checkbox" name="matchall" value="on" <?php echo isset($_GET['matchall'])?"checked":''; ?><br /><br />
     <input type="submit" name="submit" value="Search!" />
  </form>
  <?php echo (count($results) > 0)?"Your search term: {$searchTerms} returned:<br /><br />" . implode("", $results):""; ?>

The option values that are used are the name as the titles stored within stitle within the mysql database. Have I simply implemented them wrong or is my php used after title completely incorrect?

Any advice on what I can do or any code snippets from yourselves would be very appreciated.

  • 写回答

1条回答 默认 最新

  • douzhang3898 2014-11-29 02:00
    关注

    Ok I think I get your issue.

    First if you want to select more than one item in a dropdown, then you need to add the multiple attribute to the select tag like this <select name="title" multiple> Now when the user holds the CTRL key down and clicks entries, each clicked entry gets selected.

    Secondly the data identifying the selected items will now be returned as an array in $_GET['title'] so if the first 2 options are selected the $_GET['title'] array would look something like this :-

    0 - "Test Simple Search 1"
    1 - "Searching Made Easy 101"
    

    Now in order to re-select the items that were selected by the user when they submitted the form you have to set the selected="selected" attribute on each of the <option> tags that equate to the selected rows of the dropdown so they look selected when the user sees the form again.

    <?php
        function was_i_selected($selected_options, $value) {
            if ( in_array($value, $selected_options, true) ) {
               return 'selected="selected"';
            } else {
               return NULL;
            }
        }
    ?>
    
     <select name="title" multiple>
     <option <?php echo was_i_selected($_GET['title'], 'Test Simple Search 1');?> value="Test Simple Search 1">Test Simple Search</option>
    
     <option <?php echo was_i_selected($_GET['title'], 'Searching Made Easy 101');?> value="Searching Made Easy 101">Search Made Easy</option>
    
     <option <?php echo was_i_selected($_GET['title'], 'Gateway to Information');?> value="Gateway to Information">Gateway to Information</option>
    
     <option <?php echo was_i_selected($_GET['title'], 'The Gaming World as we Know it');?> value="The Gaming World as we Know it">Gaming World</option>
    
     <option <?php echo was_i_selected($_GET['title'], 'Hundreds of Ants Attacking');?> value="Hundreds of Ants Attacking">Ants Attacking</option>
    
    </select>
    

    Now that look very clumsy and we have not checked that $_GET['title'] actually exists, so I would probably do it like this :-

    <?php
        $options = array(
                 'Test Simple Search 1' => 'Test Simple Search',
                 'Searching Made Easy 101' => 'Search Made Easy',
                 'The Gaming World as we Know it' => 'Gaming World',
                 'Hundreds of Ants Attacking' => 'Ants Attacking'
                );
    
    <select name="title" multiple>
    <?php
        foreach ( $options as $val => $label ) {
            if ( ! empty($_GET['title'] ) {
                $sel = in_array($val, $_GET['title'], true) ? 'selected="selected"' : '';
                echo '<option ' . $sel . ' value="' . $val . '">' . $label . '</option>';
            } else {
                echo '<option value="' . $val . '">' . $label . '</option>';
            }
        }
    ?>
    </select>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)