1

我正在尝试从我的 MySQL 数据库中选择所有值。选项 a、b 和 c 工作正常,但我不确定选择所有三个的语法。

<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="1,2,3">All</option>
4

3 回答 3

5

如果我正确理解您的问题并通过查看您的“全部”选项的值,我认为您想使用选择来获取一个项目或所有项目。

如果是这样,请将您的选择选项的值全部更改为<option value="all">all items</option>.

然后将您的 PHP 文件(您使用表单发布到的位置)更改为:

// is the all option send?
if($_POST['your_select'] === 'all') {
    //query to get all the items (SELECT * FROM table)
} else {
    // query with the post value as the id (SELECT * FROM table WHERE id = $_POST['your_select'])
}
于 2012-12-05T13:16:29.870 回答
0

尝试这个

<form action="my_page.php" method="post">
    <select name="my_select">
        <option value="1">a</option>
        <option value="2">b</option>
        <option value="3">c</option>
        <option value="1,2,3">All</option>
    </select>
    <input type="submit" name="submit" value="Submit" />
</form>


<?php
# in my_page.php page

# put submitted value of the select tag in an array 
# (submitted value in this case equals "1", "2", "3" or "1,2,3")
$values = explode(",", $_POST["my_select"]);

# get number of values in the array
$num_of_values = count($values);

# escape all values before using them in your sql statement
foreach ($values as $key => $val) {
    $values["$key"] = mysql_real_escape_string($val);
}

# if we have more than 1 value in the array 
if (count($values) > 1) {
    $sql = "SELECT * FROM table_name WHERE "; # note the space after "WHERE" keyword

    for ($i = 0; $i < $num_of_values; $i++) {
        # this "if" statement is for removing the "OR" keyword from the sql statement 
        # when we reach the last value of the array
        if ($i != $num_of_values - 1) {
            $sql .= "column_name = '{$values[$i]}' OR "; # note the space after "OR"
        } else { #if we reached the last value of the array then remove the "OR" keyword
            $sql .= "column_name = '{$values[$i]}'";
        }
    }

    # execute your query
    $result = mysql_query($sql);
} else { # if we have only one value in the array
    $result = mysql_query("SELECT * FROM table_name WHERE column_name = '{$values[0]}'");
}

?>
于 2012-12-05T14:56:40.133 回答
0

我想你想要multiple="multiple"它允许你选择多个

<select name="modules[]"  multiple="multiple">
   <option value="1">a</option>
   <option value="2">b</option>
   <option value="3">c</option>
   <option value="1,2,3">All</option>
</select>

现在您将获得所选选项的数组,您可以通过GETPOST

要选择最后选择的所有内容,您可以使用 jquery 之类的

$('option').click(function(){
   if($(this).val() =='1,2,3'){
    $("option").attr("selected", "selected");
   }

})
于 2012-12-05T13:09:36.247 回答