I am trying to filter out a MYSQL table according to user selected values in my php file list.php
My table users
have field stdYr
, in which elements have values of S00, S01, ... S40
.
in html body, I have this chunk of code:
<form method="post" role="form" action="list.php">
<div>
<select multiple>
<option value="all">Select</option>
<option value="S00">74</option>
<option value="S01">75</option>
<option value="S02">76</option>
...
<option value="S40">114/option>
</select>
<button type="submit"></button>
</div>
</form>
And then, I want to select those with selected stdYr
values. The approach I could come up with is passing the values of option
through $_POST
:
if(isset($_POST['S00']) || isset($_POST['S11']) || ...
... || isset($_POST['S40'])) {
/*some code to get only those set values*/
$query="SELECT * FROM users WHERE stdYR = '/*some stuff*/'";
}
But with different possible selections of values, I couldn't figure out how exactly to do this... And even with the solution, I see this approach very repetitive and silly. How am I supposed to deal with such things?
I greatly appreciate your help! Thanks :D
Your form is incorrect. Your select
MUST have a name
attribute for it to get submitted to the server.
<select name="options[]" multiple>
^^^^^^^^^^^^^^^
<option ...>
...
</select>
Note the []
on the name field. That'll tell PHP to accept multiple values, making $_POST['options']
an array itself. Then it's a simple matter of:
foreach($_POST['options'] as $option) {
insert_into_db($option);
}
Use this way:
<form method="post" role="form" action="list.php">
<div>
<select name="MyOptions[]" multiple>
<option value="all">Select</option>
<option value="S00">74</option>
<option value="S01">75</option>
<option value="S02">76</option>
...
<option value="S40">114/option>
</select>
<button type="submit"></button>
</div>
</form>
print '<pre>';
print_r($_POST);
$selectOption = $_POST['MyOptions']; //get post result and then work as you wish
You could try this :
<select name="stdYR[]" multiple>
<?php
$stdYR = $_POST['stdYR'];
$stdYR_ct = count($stdYR);
$i=0;
while($i < $stdYR_ct){
$stdYR_SQL .= "'$stdYR[$i]',";
$i++;
}
if (preg_grep("/All/i", $stdYR) or ($stdYR_ct < 1)){
$stdYR_SQL = "";
}else{
$stdYR_SQL = eregi_replace(",$",'',$stdYR_SQL);
$stdYR_SQL = " AND stdYR IN($stdYR_SQL)";
}
$query = "SELECT * FROM users WHERE 1=1 $stdYR_SQL ";
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.