选择所有选项值php mysql

时间:2012-12-05 13:06:20

标签: php mysql drop-down-menu

我正在尝试从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>

3 个答案:

答案 0 :(得分:4)

如果我正确理解您的问题并查看“所有”选项的值,我认为您想要使用select来获取项目或所有项目。

如果是,请将所有选项的值更改为<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'])
}

答案 1 :(得分:1)

试试这个

<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]}'");
}

?>

答案 2 :(得分: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");
   }

})