I`m using this code to repopulate drop down list from the database :
$city_id = 15;
while($row = mysql_fetch_assoc($result)) {
$selected = ($row['city_id'] == $city_id) ? 'selected="selected" ' : NULL;
echo '<option value="'.$city_id .$selected . '">"'.$row['city_name'].'"</option>\n';
}
It`s work like a charm but my question is are they more elegance solutions ?
Other than improving the indentation of the code, this is fine.
$city_id = 15;
while($row = mysql_fetch_assoc($result))
{
$selected = ($row['city_id'] == $city_id) ? ' selected="selected"' : NULL;
echo '<option value="' . $row['city_id']. '"' . $selected . '>'.$row['city_name'].'</option>\n';
}
Well, a more elegant solution would be to have a "controller" file that fetches all the cities an puts them into an array/object list/whatever. Then, in a "view" file, you iterate over that variable. That way, you separate a bit more the presentation from the logic.
In view:
<select name=student value=''>Student Name</option>
<?php foreach($cities as $city): ?>
<option value="<?php echo $city->id ?>" ><?php echo $city->name ?></option>
<?php endforeach; ?>
</select>
Also, I'd highly recommend using PDO for DB access.
I always use a function, since select boxes are something I end up creating a lot...
function select($name, $default, $values, $style='', $param='') {
$html = '<select name="'.$name.'" style="'.$style.'" '.$param.' >';
foreach($values as $i => $data) {
if (isset($data['noFormat'])) {
$html .= '<option value="'.$data['value'].'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.$data['text'].'</option>';
} else {
$html .= '<option value="'.htmlentities($data['value']).'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.htmlentities($data['text']).'</option>';
}
}
$html .= '</select>';
return $html;
}
Then loop through your query to build the array like this:
$default[] = array('value' => '0', 'text' => 'Select a City...');
while($row = mysql_fetch_assoc($result)) {
$list[] = array('value' => $row['city_id'], 'text' => $row['city_name']);
}
$list = array_merge($default,$list);
And finally an example to create the HTML:
select('select','form_el_name',$list['0'],$list,'font-size:12px;','onChange="document.forms[0].submit();"');
Hope it helps!
mysql_fetch_assoc to mysql_fetch_array
add proper comments
use standard php class ezsql or simple class tuts
$query="SELECT name,id FROM student";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);
echo "<select name=student value=''>Student Name</option>";
// printing the list box select command
while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=$nt[id]>$nt[name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";//Closing of list box
Related
There a few schools under HQ and same things goes to franchise. I want to create a dropdown list when I click "Centre" to create new data, it will also create a new data for the all schools who have been group by centre
Here is my controller
$this->centre= $this->db->get_where('schools', array('group_by'=>'centre'))->result();
And this is views
<?php foreach ($centre as $c) { ?>
<option value="<?php echo $c->id; ?>" <?php if(isset($school_id) && $school_id == $c->id){echo 'selected="selected"';} ?>><?php echo $c->school_name; ?></option>
<?php } ?>
I want to create like this, this is just an example
$this->centre will not get the data to your view. You need to pass that data into your view like this:
Codeigniter 2, 3
$centre= $this->db->get_where('schools', array('group_by'=>'centre'))->result();
$this->load->view('view-file', array('centre' => $centre));
Codeigniter 4
$centre= $this->db->get_where('schools', array('group_by'=>'centre'))->result();
echo view('view-file', array('centre' => $centre));
Try this my friend
$output = '<select>';
foreach( $center as $key => $c ) {
$selected = (isset($school_id) && $school_id === $c->id) ? 'selected="selected"' ? '';
if( $key === 0 ) {
$output .= '<option value="">--Select School--</option>';
}
$output .= '<option value="'.$c->id.'" '.$selected .'>
$output .= $c->school_name;
$output .= '</option>';
}
$output .= '</select>';
echo $output;
or using CI form helper
$options = array();
$selected = '';
foreach( $center as $key => $c ) {
$options[$c->id] = $c->school_name;
$selected = (isset($school_id) && $school_id === $c->id) ? $c->id ? '';
}
echo form_dropdown('select_tag_name', $options, $selected);
So I am creating a dynamic menu. Where I have stored the main categories of the menu in a separate table and subcategories in another table.
They are stored in this way
Categories Table
id cat_name
1 HOME,
2 PRODUCTS,
3 SOLUTIONS,
4 NEWS & GALLERY,
5 DOWNLOADS,
6 CONTACT
Right Now I am running a query
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($query)) {
$row['cat_name'];
$cat=explode(",",$row['cat_name']);
}
Then wherever needed I am printing the values like this
<?php echo $cat[0]; .. echo $cat[1]; //and so on ?>
It looks like this right now. And it is supposed to look likethis
But the problem with this solution is that I have to define the index of the array to print it.
I am developing the admin panel for this one and I want that if the admin adds a new menu item then it should automatically fetch it and display it.
But with this solution it is not possible.
I am thinking of iterating the values with a for loop but cannot get it right.
Use foreach ($query as $rows)
or
Use for ($i=0; $i < count($query); $i++)
Probably You can try this also
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($query))
{
$row['cat_name'];
$cat=explode(",",$row['cat_name']);
foreach($cat as $catss)
{
$cat = trim($catss);
$categories .= "<category>" . $cat . "</category>\n";
}
}
You can try this way may be you wish like this for dynamic menu:
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
$menu = '';
$menu .= '<ul>';
while($row = mysqli_fetch_assoc($query))
{
$menu .= '<li>' . $row['cat_name'] . '</li>';
}
$menu .= '</ul>';
echo $menu;
When you are fetching data from table then you can directly print that value using field name. if you want to further use that so, you have to add in one array like:
$cat[] = $row['cat_name'];
then you can use this value in that manner using for or while:
foreach ($cat as $value) {
echo $value;
}
echo '<ul>';
foreach ($cat as $val) {
echo "<li>{$val}</li>";
}
echo '</ul>';
Instead of the index. Also this should be faster and readable than for loop.
You can save it in array then later access the values.
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
$cat = array();
while($row = mysqli_fetch_assoc($query)) {
$cat[]=$row['cat_name']
}
Now:
foreach ($cat as $category) {
$cate_gory = explode("," , $category);
foreach ($cate_gory as $categories) {
echo $categories . "<br>";
}
}
Foreach Loop
foreach($cats as $cat)
{
echo $cat;
}
Basic For Loop
for ($i=0; $i<count($cats); $i++)
{
echo $cats[$i];
}
Simple Use Case
<?php
$cats = 'Stack overflow PHP questions';
$cats = explode(' ',$cats);
$html = '<ul>';
foreach($cats as $cat)
{
$html .= '<li>' . $cat . '</li>';
}
$html .= '</ul>';
echo $html;
?>
Your Code
In this case the while loop you are using will iterate over all the values returned from the sql statement, so there is no need to add more complexity. I would remove the commas from the field names and echo out the html this way.
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
$html = '<ul>';
while($row = mysqli_fetch_assoc($query)) {
$html .= '<li>' . $row['cat_name'] . '</li>';
}
$html .= '</ul>';
echo $html;
?>
How can i create a Multiple select box from 2 arrays
1st array contains all values and the second array contains the values that will be marked as selected in multiple select
$a=array[1,2,3,4,5,6,7,8];
$b=array[3,7,8];
the multiple selectbox will have all the values from array $a but values from array $b will be selected.
Any way to achieve this ?
You can use this code
$a=array(1,2,3,4,5,6,7,8);
$b=array(3,7,8);
$selected="";
foreach($a as $val)
{
if(in_array($val,$b))
{
$selected = 'selected="selected"';
}
//Code for create multi select drop down and echo $selected in option like
<option $selected value="" ></option>
}
$a=array(1,2,3,4,5,6,7,8);
$b=array(3,7,8);
$html = '<select multiple>';
foreach($a as $val)
{
$selected = (in_array($val,$b)) ? 'selected' : '';
$html .= '<option value="' . $a . '"' . $selected . '>' . $a . '</option>';
}
$html .= '</select>';
echo $html;
How can I retrieve the values from a table which I stored in a column using a text box by comma separated.
Like:
Enter Member Names: [raj, ram, john, mop]
It has been stored in a column as this is [raj, ram, john, mop]; on site I want it in a select option:
Select Member:
<option>raj</option>
<option>ram</option>
<option>john</option>
<option>jonh</option>
Option will be so on, how to resolve it. any query to retrieve this type of data
you work like this
$query=mysql_fetch_assoc(mysql_query("select * from table_name"));
$exp=explode(",",$query['col_name']);
foreach($each as $exp)
{
?>
<option value="<?php echo $each[0];?>"><?php echo $each[0];?></option>
<option value="<?php echo $each[1];?>"><?php echo $each[1];?></option>
<option value="<?php echo $each[2];?>"><?php echo $each[2];?></option>
<option value="<?php echo $each[4];?>"><?php echo $each[3];?></option>
<?php
}
Try to use
<?php echo '<select name="name">';
$list = explode(',', $value);
foreach ($list as $item)
{
echo '<option value="' . $id . '">' . $item . '</option>';
}
echo '</select>';
$query = "SELECT member_name FROM users";
// after getting the result
$resultArray = explode(",",$ft['members']); // $ft['members'] is "raj, ram, john, mop"
foreach($resultArray as $value) {
echo $value;
echo "<br>";
}
I have a dropdown section menu that I need to set the selected value based on the database values.
I have a table with the following structure: id, pid, disporder, title, url
I am then using this code for the dropdown:
echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
echo "<option value=\"".$parent['id']."\">".$parent['title']."</option>";
}
echo "</select>";
How would I go by getting the selected value based on what's in the database?
I have multiple entries in the table, so using an array with values (similar to this), isn't what I want to use:
$options = array('1', '2', '3');
foreach($options as $option)
{
if($option = $parent['id'])
{
echo "selected";
}
else
{
echo "";
}
Thanks.
You haven't really given enough info to really say what the exact solution would be. If you're creating a select tag in PHP though, the typical pattern for building the markup is:
<?php
$options = get_me_some_options();
$select_markup = '<select name="my-select" id="my-select>';
foreach ($options as $key => $val) {
$selected = '';
if (is_this_selected($val)) {
$selected = 'selected';
}
$select_markup .= "<option $selected val=\""
. $val['id'] . "\">" . $val['name'] . '</option>';
}
echo $select_markup . "</select>";
It looks like your use case is similar, but slightly more complex. Ultimately though what matters is that, inside the loop, you have some way to determine whether a given row should be 'selected' or not.
If I understand correctly, you want to compare each $parent['id'] with the values of an array called $options. Try this:
$options = array('1', '2', '3');
echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
$selected = ( in_array($parent['id'], $options) ? ' selected' : '';
echo "<option value=\"".$parent['id']."\"$selected>".$parent['title']."</option>";
}
echo "</select>";
If you're trying to use this in multiselects then this might help
<?php
$optionsToSelect=array(1,2,3);
?>
<select name="parent" id="parent">
<?php
foreach($allOptions as $opt){
?>
<option value="<?php echo $opt['value'];?>" <? echo $opt['selected']==1?'selected="selected"':'';?>><?php echo $opt['optTitle'];?><option>
<?php
}
?>
</select>