How would I go about setting the "selected" attribute to one of these boxes, based on what value is stored in the $genre variable?
i.e. If $genre == "Puzzle" then
<option value=Puzzle>
becomes
<option value=Puzzle selected>
Here is my current code:
<?php
$query = "SELECT * FROM release_dates WHERE id = $id";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$genre = $row['game_genre'];
?>
<select name=genre>
<option value=Action>Action</option>
<option value=Adventure>Adventure</option>
<option value=Puzzle>Puzzle</option>
<option value=RPG>RPG</option>
<option value=Horror>Horror</option>
<option value=Shooter>Shooter</option>
<option value=Simulator>Simulator</option>
<option value=Sport>Sport</option>
<option value=Strategy>Strategy</option>
</select>
Also, for extra brownie points, how would this apply to select boxes with the "multiple" attribute?
Any help or ideas would be greatly appreciated.
Well, that's pretty simple actually:
<option value=Action <?php $genre == "Action" ? "selected":""?> >Action</option>
Just use a ternary operator (condition) ? true:false to input "selected" if the value is set. Simply duplicate that logic on all the options:
<option value=Action <?php $genre == "Action" ? "selected":""?> >Action</option>
<option value=Adventure <?php $genre == "Adventure" ? "selected":""?> >Adventure</option>
<option value=Puzzle <?php $genre == "Puzzle" ? "selected":""?> >Puzzle</option>
<option value=RPG <?php $genre == "RPG" ? "selected":""?> >RPG</option>
Hope that helps!
You could use a foreach loop to iterate over your options, and each time, perform a check using an if statement to see if it matches:
foreach ($genres as $genre) {
if ($genre === "Puzzle") {
echo '<option value="'.$genre.'" selected>'.$genre.'</option>';
else {
echo '<option value="'.$genre.'">'.$genre.'</option>';
}
}
By the way, you shouldn't be using mysql_* functions anymore as they are unsafe, deprecated, and will be removed from PHP in the future. Take a look at PDO.
<option value="Strategy" <?php if($genre == "Strategy"){ echo 'selected="selected"';} ?> >Strategy</option>
I came up with a version that keeps everything in PHP
<?php
$query = "SELECT * FROM release_dates WHERE id = ". $id;
$result = mysql_query($query);
$row = mysql_fetch_array($result);
// possible options
$genre_options = array(
'Action'
'Adventure'
'Puzzle'
'RPG'
'Horror'
'Shooter'
'Simulator'
'Sport'
'Strategy'
);
// loop over the options, and wrap them in tags
$options = '';
foreach ($genre_options as $genre) {
// check if we have a match
$selected = '';
if ($genre == $row['game_genre']) {
$selected = 'selected="selected"';
}
$options .= '<option value="'. $genre .'" '. $selected .'>'. $genre .'</option>'
}
echo '
<select name=genre>
'. $options .'
</select>
';
?>
What this does is create an array of possible genre's, loop over them, and see if any of them match the genre that was returned from the query. If thats the case it will add the selected="selected" attribute.
Unfortunately I'll be missing out on the "brownie points", because I'm not able to help you with the multi-select.
Let me know if this helps!
EDIT: I also noted that in your query you where passing the $id variable as a string. Fixed that in the query in my example.
Instead of defining your genres using plain HTML, create an array with all your genres.
To do so:
$genres = array(
"Action",
"Adventure",
"Puzzle",
"RPG",
"Horror",
"Shooter",
"Simulator",
"Sport",
"Strategy"
);
foreach($genres as $currentGenre) {
echo "<option value="'.$currentGenre.'" '.($currentGenre == $genre ? "selected" : "").'>'.$currentGenre.'</option>';
}
What this does, is loop over all your genres and create a single <option> for each of them. If the $currentGenre (so one of the genres from the array $genres) matches $genre (which you pulled from MySQL), it selects that option using a inline if-statement.
Related
I have recursion function which populates data on my select drop down.
How can I pass a value that, if it matches with any value on drop down, gets selected?
this is function on my model:
function get_all_cat($parent,$level=0,$s){
$ui = '';
$this->db->order_by($this->id, $this->order);
$this->db->where('parent',$parent);
$query=$this->db->get($this->table)->result();
foreach ($query as $qu) {
if($s==$qu->id){
$y = 'selected';
}
$repeat = str_repeat('--', $level);
$ui .= '<option value="'. $qu->id .'" '.$y.' >' .$repeat. $qu->title.'</option>';
$new_level = $level+1;
$ui .= '' .$this->get_all_cat($qu->id,$new_level) .'';
}
return $ui;
}
and here is my select option in the view:
<div class="form-group">
<select name="category" class="form-control chosen-select">
<option value="">Any Category</option>
<?php
$cat = $this->Dbc_categories_model->get_all_cat(0,0,$this-session->userdata('clicked_id');
echo $cat;
?>
</select>
</div>
few notes that I pick up...
1.) Don't ever use variable names like $s => easy to lost track and that name doesn't tell you what variable contain or do
2.) You're not passing selected value to reclusive function (missing third parameter)
Otherwise looks like this are working code.
This is sort of an extension of the problem solved here: Set default value for HTML select control in PHP however I would like to fill in Multiple values that match, with the values to fill in stored in an additional array:
This is my code so far:
<select name="genres[]" id="genres_edit" multiple>
<?php
$genrelist = array(
'Action',
'Adventure',
'Comedy',
'Cooking',
'War',
'Western');
for($i = 0;$i < count($genrelist);$i++) {
echo "<option value=\"$genrelist[$i]\"";
for ($g = 0; $g < count($genre);$g++) {
if ($genrelist[$i] == $genre[$g]) {
echo "selected=\"selected\"";
}
echo ">$genrelist[$i]</option>";
}
}
?>
</select>
$genrelist is the array of all possible genres that will be used to fill up the select control, and the array of actual genres is stored in $genre.
Basically I want it to highlight the values in the selectbox that match any of the values in the $genre array.
i.e. if the genres stored in $genres are: Adventure, Cooking, Western, then those 3 values will be highlighted in the select box, out of the 6 available genres in the box.
Here's how I'd do it ...
$genres = array(
'Action',
'Western'
);
$genrelist = array(
'Action',
'Adventure',
'Comedy',
'Cooking',
'War',
'Western');
foreach ($genrelist as $k=>$v) {
$sel = (array_search($v,$genres) !== false) ? ' selected' : '';
echo '<option value="'. $k .'"'. $sel .'>'. $v .'</option>';
}
Here's the sandbox ... http://sandbox.onlinephpfunctions.com/code/e4f2ca28e0fd43513b694f5669329cc1db328598
Assuming your form in being set with method="get" then the $_GET superglobal should have an array in it called genres (as defined by the fact that your multiple select box is called genres[]).
So when looping through your output you should be able to check if the current genre (from the $genrelist array) exists in the $_GET['genres'] array ... like so:
<?php
$genrelist = array(
'Action',
'Adventure',
'Comedy',
'Cooking',
'War',
'Western');
?>
<select name="genres[]" id="genres_edit" multiple="multiple">
<?php foreach($genrelist as $genre): ?>
<?php $sThisSelected = in_array($genre, $_GET['genres']) ? " selected=\"selected\"" : ""; ?>
<option value=\"<?= $genre; ?>\"<?= $sThisSelected; ?>><?= $genre; ?></option>
<?php endforeach; ?>
</select>
There's no sanity checking or sanitisation in this but that's the theory anyway.
If you want multiple selection you must specify your select tag with multiple option
<select multiple="1">
<option selected>option1</option>
<option selected>option1</option>
<option selected>option1</option>
</select>
The drawback is that the select menu is no more a dropdown, if that matter for you, let me know and I will try to tune in the solution.
I have a mysql entry as an integer 1 to 10. I want to display the result pre selected in a drop down. I am using -
<select name="Sleeps">
<?php
$sleeps = $row['Sleeps'];
$selectedId = array(1, 2, 3);
$selection = array(
1 => "1",
2 => "2",
3 => "3" );
foreach($selection as $value){
$text = $value;
$selected = '';
if ($selectedID == $sleeps) {
$selected = 'selected';
}
echo '<option value="'.$text.'" selected="'.$selected.'">'.$text.'</option>';
}
?>
</select>
This nearly works as I get -
<option value="1" selected="selected">1</option>
<option value="2" selected="selected">2</option>
<option value="3" selected="selected">3</option>
But all options have selected="selected" and i just want the value I have in my db selected which I believe should just be 'selected' text like -
2
Please help I am new to this
I think this is types mistake. Try using "===" or if this rows is text convert to int
How contert text to int
if ($selectedID == $sleeps) {
$selected = 'selected';
}
Should be
if ($text == $sleeps) {
$selected = 'selected';
}
selectedID isn't defined anywhere, however, selectedId is, and if you want it to be sleected for any number in the array, use
if (in_array($sleeps, $selectedID)) {
$selected = 'selected';
}
I am trying to get a select list with values from $staff
The bit i am struggling is selecting the staff that are already enrolled from $entry->enrolments.
If the $staff id exists in $entry->enrolments select it in the select list
$entry = Record from mysql
$staff = list of staff in an array.
$entry->enrolments = comma seperated values of enrolled staff
<select name="tutor[]" id="tutor" multiple="multiple" size="5" class="required" title="Select Staff">
<?php
$entry = get_record("staff_development", "id", $id);
$staff = get_records("user", "deleted", "0", "lastname ASC", "id,firstname,lastname,idnumber");
$sdenrolments=array($entry->enrolments);
$people = explode(",", $entry->enrolments);
foreach($staff as $tutor){
foreach($people as $person){
if($tutor->id>1)echo '<option value="'.$tutor->id.'"';
if ($person==$tutor->id) {echo 'selected="selected"';}
echo '>'.$tutor->lastname.' '.$tutor->firstname.'</option>';
}
}
?>
</select>
Any help/guidance would be greatly appreciated.
Thanks in advance
in_array is the easiest way to tell if a value is in an array :) Replace your loops with this:
foreach($staff as $tutor){
echo '<option value="'.$tutor->id.'"';
if(in_array($tutor->id, $people))
echo 'selected="selected"';
echo '>'.$tutor->lastname.' '.$tutor->firstname.'</option>';
}
You might also want to rename your variable from people to enrolled_staff or something a bit more clear.
Your if block is confusing. You are checking for $tutor->id > 1 when opening the option tag, but aren't when closing it. PaulP.R.O mentions in_array which you should replace your foreach loops with. Here is your if block cleaned up and set the check for selection inline.
if($tutor->id > 1) {
echo '<option value="'.$tutor->id.'" ' . (($person==$tutor->id) ? ' selected="selected"': '') . '>';
echo $tutor->lastname.' '.$tutor->firstname;
echo '</option>';
}
I am currently creating a multiple dropdown query where the user can query by (3) factors for returning results, my issue is how can I do this in an efficient manner so I am not obscurely writing multiple possible MySQL Queries.
<select name="class">
<OPTION VALUE='any'>Choose Class
<option value="a">Block A</option>
<option value="b">Block B</option>
<option value="c">Block C</option>
</select>
<select name="category">
<OPTION VALUE='any'>Choose Type
<option value="math">Math</option>
<option value="science">Science</option>
<option value="history">History</option>
</select>
How can I successfully create a MySQL query that will correctly select the right parameters in the case that a variable is missing. In example, if they choose to do the first dropdown and only search for the "class" and not choose the second dropdown. I want to be able to do the first query, the second query or both of them. I have the PHP, Ajax written, I'm just stumped as to the correct structure of the MySQL query.
Put your "WHERE" clause conditions in one array. I would do like this:
// filter out invalid values is important
$valid_class = array('a', 'b', 'c');
$valid_category = array('math', 'science', 'history');
// initialize array for WHERE clause conditions
$where = array('TRUE');
if (in_array($_POST['class'], $valid_class))
{
$where[] = 'class = "' . $_POST['class'] . '"';
}
if (in_array($_POST['category'], $valid_category))
{
$where[] = 'category = "' . $_POST['category'] . '"';
}
// use the array with the "implode" function to join its parts
$sql = 'SELECT * FROM table WHERE ' . implode(' AND ', $where);
You may want to initialize the $where array with something more interesting than "TRUE" (which is there in case the user does not filter by class neither category, because we don't want an empty $where array reaching the last line). For example:
$where = array();
$where[] = 'name = "' . mysql_real_escape_string($_POST['name']) . '"';
<select name="class">
<OPTION VALUE="">Choose Class
<option value="a">Block A</option>
<option value="b">Block B</option>
<option value="c">Block C</option>
</select>
<select name="category">
<OPTION VALUE="">Choose Type
<option value="math">Math</option>
<option value="science">Science</option>
<option value="history">History</option>
</select>
set the column of the table on ur MySQL to allow null
so when user select " <OPTION VALUE="">Choose Type" or "<OPTION VALUE="">Choose Class", pass Null into the column
Break the query in pieces and use it conditionally
suppose: $class is for class select box and $category is for category select box
$selectquery = "select * from tablename ";
if($class != "" && $category == ""){
$selectquery .= "WHERE class='".$class."'";
}elseif($class == "" && $category != ""){
$selectquery .= "WHERE category ='".$category."'";
}elseif($class != "" && $category != ""){
$selectquery .= "WHERE category ='".$category."' AND class='".$class."'";
}