How to fetch data from database and display in html dropdown? - php

I am creating a simple form with fields like First_name, Last_name, city etc.So for city field, I want to display dynamic data.Below is the code I am using it's in PHP CodeIgniter.
Controller Page:
public function city()
{
$this->load->model('dropdownM');
$getcity=$this->dropdownM->get_city();
$this->load->view('form1city',$getcity);
}
Model Page:
<?php
class DropdownM extends CI_Model
{
public function get_city()
{
$this->db->select('fname');
$this->db->from('city');
$query = $this->db->get();
if($query->num_rows()>0)
{
return $query->result();
}
}
}
View page:
<form action="<?php echo base_url(); ?>index.php/Rec/user" method="post">
<select class="form-control" id="city" name="city">
<option value="">Select </option>
<?php if(count($getcity)):?>
<?php foreach($getcity as $city):?>
<option value=<?php echo $city->c_id;?>><?php echo $village1->C_name;?></option>
<?php endforeach;?>
<?php else:?>
<?php endif;?>
</select>
<center>
<input type="submit" value="Submit" class="btn btn-bricky" id="subbtn"
name="submit1">
</center>
<form>
It's not displaying anything in the drop-down.I am not able to find out what the issue.

pass data like this
$data['getcity']=$this->dropdownM->get_city();
$this->load->view('form1city',$data);
and in view
<?php if(count($getcity) > 0):?>
<select class="form-control" id="city" name="city">
<option value="">Select </option>
<?php foreach($getcity as $city):?>
<option value=<?php echo $city['c_id'];?>><?php echo $village1['C_name'];?></option>
<?php endforeach;?>
</select>
<?php else:?>
<p>No Category Found</p>
<?php endif;?>
In model
$this->db->select('fname');
$this->db->from('city');
$query = $this->db->get();
return $query->result_array();

Related

How to fetch data from database and display it in a drop down list using Codeigniter

I collect data from the database table and display it in the drop-down list, here's what I've done so far
THIS IS MY CONTROLLER:
public function assign_hostel() {
$inner_page_title = 'Assign Hostel';
$this->admin_header('Assign Hostel', $inner_page_title);
$data['hostel'] = $this->hostel_model->get_hostel();
$this->load->view('admin/hostel/assign_hostel');
$this->admin_footer();
}
THIS IS MY MODEL:
public function get_hostel() { //get all hostel
$this->db->order_by('hostel_name', 'asc');
return $this->db->get_where('school_hostel', array('hostel_name' =>
$hostel_name)->result();
}
MY VIEW:
<div class="form-group">
<label class="form-control-label">Select Hostel</label>
<select class="form-control" name="state_of_origin" required>
<option value="">-Select-</option>
<?php
$hostel_name = get_hostel();
foreach ($hostel_name as $hostel ) { ?>
<option value="<?php echo $hostel; ?>"><?php echo $hostel; ?></option>
<?php } ?>
</select>
</div>
Why am I getting an empty drop-down list?
Hope this will help you :
Pass $data['hostels'] in your view as given below :
First your controller assign_hostel should be like this :
public function assign_hostel()
{
$inner_page_title = 'Assign Hostel';
$this->admin_header('Assign Hostel', $inner_page_title);
$data['hostels'] = $this->hostel_model->get_hostel();
$this->load->view('admin/hostel/assign_hostel' ,$data);
$this->admin_footer();
}
Second your view should be like this :
<div class="form-group">
<label class="form-control-label">Select Hostel</label>
<select class="form-control" name="state_of_origin" required>
<option value="">-Select-</option>
<?php if ( !empty($hostels)) {
foreach ($hostels as $hostel ) { ?>
<option value="<?=$hostel->hostel_name; ?>"><?=$hostel->hostel_name;?></option>
<?php } }?>
</select>
</div>
For more : https://www.codeigniter.com/user_guide/general/index.html
You can't get $hostel from view directly to model, you must get from controller and pass it via $data to view
CONTROLLER:
public function assign_hostel() {
$inner_page_title = 'Assign Hostel';
$this->admin_header('Assign Hostel', $inner_page_title);
$data['hostels'] = $this->hostel_model->get_hostel();
$this->load->view('admin/hostel/assign_hostel', $data);
$this->admin_footer();
}
MODEL:
public function get_hostel() { //get all hostel
$this->db->order_by('hostel_name', 'asc');
return $this->db->get_where('school_hostel', array('hostel_name' =>
$hostel_name)->result();
}
VIEW:
<div class="form-group">
<label class="form-control-label">Select Hostel</label>
<select class="form-control" name="state_of_origin" required>
<option value="">-Select-</option>
<?php
foreach ($hostels as $hostel) { ?>
<option value="<?php echo $hostel; ?>"><?php echo $hostel; ?></option>
<?php } ?>
</select>
</div>
Pass $data to view function in controller
CONTROLLER:
public function assign_hostel() {
$inner_page_title = 'Assign Hostel';
$this->admin_header('Assign Hostel', $inner_page_title);
$data['hostel'] = $this->hostel_model->get_hostel();
$this->load->view('admin/hostel/assign_hostel', $data);
$this->admin_footer();
}
And in view get $hostel
VIEW:
<div class="form-group">
<label class="form-control-label">Select Hostel</label>
<select class="form-control" name="state_of_origin" required>
<option value="">-Select-</option>
<?php
foreach ($hostel as $hostel ) { ?>
<option value="<?php echo $hostel; ?>"><?php echo $hostel; ?></option>
<?php } ?>
</select>
There are few changes you need to make:
Change 1:
Pass the $data variable when you load the view:
$data['hostel'] = $this->hostel_model->get_hostel();
$this->load->view('admin/hostel/assign_hostel', $data); // $data as 2nd argument
Change 2:
Access key of $data array as variable in view file like this:
<div class="form-group">
<label class="form-control-label">Select Hostel</label>
<select class="form-control" name="state_of_origin" required>
<option value="">-Select-</option>
<?php
//$hostel_name = get_hostel(); NO NEED THIS LINE
foreach ($hostel as $h ) { ?>
<option value="<?php echo $h->hostel_name; ?>"><?php echo $h->hostel_name; ?></option>
<?php } ?>
</select>
</div>
I still need to know what columns you are fetching. Because in <option> tag you need to use the variable to access their attributes. Right now I have used the variable $h itself which is wrong.
You should use something like $h->name;

Country state concept in codeigniter

This is My View Page
<select name="category" value="c_id" onChange="getsubcategorydetails(this.value)" style="display:">
<option value="" selected="selected" >Select Categories</option>
<?php if(isset($categories)) : foreach($categories as $row) :?>
<option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
<?php endforeach;?>
<?php else :
endif;
?>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<tr>
<td>
<select name=" select id="subcategory">
<option value="" selected="selected" >Select Sub Category</option>
<?php foreach($sub_categories as $stt): ?>
<option value="<?php echo $stt->s_c_id; ?>"><?php echo $stt->s_c_name; ?></option>
<?php endforeach; ?>
</select>
</select></td>
</tr>
This is My Controller
public function getsubcategorydetails($c_id)
{
$c_id = $this->uri->segment(3);
// echo $c_id;
$data['sub_categories'] = $this->m_category->getsubcategorydetails($c_id);
//print_r($data['sub_category']);
$this->load->view('my_admin/newpost_1',$data);
}
This is My Model
function getsubcategorydetails($c_id='')
{
$this -> db -> select('*');
$this -> db -> where('c_id', $c_id);
$query = $this -> db -> get('subcategories');
return $query->result();
}
When i Click Category Select Box The Values returned from Controller ... But It Not Displayed On View ... What's Wrong With That .... Thanks In Advance
Here in my code,
iam posting categoryid through ajax in onchange event
and getting the subcategory for the categoryid from controller
and make the selection box in controller with the subcategory
and put the selection box in subcategory id.
Try this method.
View file
<select name="category" onChange="getsubcategorydetails(this.value)" >
<option value="" >Select Categories</option>
<?php if(isset($categories)) : foreach($categories as $row) :?>
<option value=<?php echo $row->c_id; ?>><?php echo $row->c_name; ?></option>
<?php endforeach;?>
<?php else :
endif;
?>
</select>
<select name="subcategory" id="subcategory">
<option value="" >Select Sub Category</option>
</select>
Controller
public function getsubcategorydetails($c_id)
{
$c_id = $this->input->post('c_id');
$sub_categories = $this->m_category->getsubcategorydetails($c_id);
$subcategory='<option value="" >Select Sub Category</option>';
foreach($sub_categories as $stt)
{
$subcategory.='<option value="'.$stt->s_c_id.'">'.$stt->s_c_name.'</option>';
}
echo $subcategory;
}
Model
function getsubcategorydetails($c_id='')
{
$this -> db -> select('*');
$this -> db -> where('c_id', $c_id);
$query = $this -> db -> get('subcategories');
return $query->result();
}
Script
function getsubcategorydetails(c_id)
{
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>yourcontroller/yourfunction",
data: {c_id:c_id},
success: function(data) {
$('#subcategory').html(data);
}
});
}
I suggest you to use JQuery AJAX to fetch the subcategory details.
Currently you are following wrong coding methods like calling a codeigniter controller function on an "OnChange" event with getsubcategorydetails($c_id) which is not right and makes it a wrong practice. OnChange event is used to call only Javascript functions.
To manipulate DOM, use Javascript/JQuery for it. Use the controller as a relay for getting appropriate formatted data into your JQuery.
Better option is Fetch data using AJAX and Append that to dependent select box onChange Event.

Php Jquery Set Multiple selected values from database

I have three multiple select menus. I am trying to select the options returned from a database query. It is not setting any options. I console log the arrays returned by php and they are displayed as:["5233", "7148"]["5233", "5437", "5316"]["7029", "7852", "5525"].
I am not concerned about the form submission at this point. I only want to display the values returned from the db query as selected. I am sure there is something I am missing but can't seem to figure it out. I appreciate all the help I get. Thank you in advance!!
First are my 3 database arrays that are created:
Second is my html:
Third is my javascript/jQuery:
I have three multiple select menus. I am trying to select the options returned from a database query. It is not setting any options. I console log the arrays returned by php and they are displayed as:["5233", "7148"]["5233", "5437", "5316"]["7029", "7852", "5525"].
I am not concerned about the form submission at this point. I only want to display the values returned from the db query as selected. I am sure there is something I am missing but can't seem to figure it out. I appreciate all the help I get. Thank you in advance!!
First are my 3 database arrays that are created:
Second is my html:
Third is my javascript/jQuery:
<?
$huntNum = $hunts[$i][$fm_hunt_fields['__id']];
$cookRole = 'Cook';
$cookVols = get_volunteersByHunt($huntNum, $cookRole);
foreach ($cookVols as $cVols) {
//create new cook array that only contains ID of person
$exCooks[] = $cVols['_id_acct'];
}
$guideRole = 'Hunt Guide';
$hgVols = get_volunteersByHunt($huntNum, $guideRole);
foreach ($hgVols as $hVols) {
$exHg[] = $hVols['_id_acct'];
}
$supportRole = 'General Support';
$gsVols = get_volunteersByHunt($huntNum, $supportRole);
foreach ($gsVols as $gVols) {
$exGs[] = $gVols['_id_acct'];
}
?>
<script>
var existing_cooks = <?= json_encode($exCooks); ?>
var existing_hgs = <?= json_encode($exHg); ?>
var existing_gss = <?= json_encode($exGs); ?>
</script>
<form action="" name="vol-update" id="vol-update" class="vol- update" method="post">
<input type="hidden" id="id_hunt" name="id_hunt" value="<?= $huntNum; ?>" />
<input type="hidden" name="action2" id="action2" value="1" />
<table class="tyhp-account">
<tr>
<td>
<div class="floatL cont_lft_side">
<label for="cooks"><strong>Cooks</strong></label>
<select name="cook[]" class="form-control vCooks" multiple="multiple">
<?php
foreach ($cooksArray as $cook) {
?>
<option
<?
if (in_array($cook['ID'], $exCooks)) {
echo "selected='selected'";
}
?>
value="<?= $cook['ID']; ?>" >
<?= $cook['name_last'] . $cook['name_first']; ?>
</option>
<?
}
?>
</select>
</div>
</td>
<td>
<div class="floatL cont_lft_side">
<label for="hunt_guides"><strong>Hunt Guides</strong></label>
<select name="huntGuide[]" class="form-control vHg" multiple="multiple">
<?php
foreach ($guidesArray as $guide) {
?>
<option
<?
if (in_array($guide['ID'], $exHg)) {
echo "selected='selected'";
}
?>
value="<?= $guide['ID']; ?>" >
<?= $guide['name_last'] . $guide['name_first']; ?>
</option>
<?
}
?>
</select>
</div>
</td>
<?php
$allVols = getAllVolunteers();
?>
<td>
<div class="floatL cont_lft_side">
<label for="supp"><strong>General Support</strong></label>
<select name="gsupport[]" class="form-control vSupp" multiple="multiple">
<?php
foreach ($allVols as $allVol) {
?>
<option
<?
if (in_array($allVol['__id'], $exGs)) {
echo "selected='selected'";
}
?>
value="<?= $allVol['ID']; ?>" >
<?= $allVol['name_last'] . $allVol['name_first']; ?>
</option>
<?
}
?>
</select>
</div>
</td>
</tr>
<tr>
<td> </td>
<td style="text-align:center">
<input type="submit" name="action" id="upVol" class="btn btn-primary" value="Update Volunteers">
</td>
<td> </td>
</tr>
</table>
</form>
//Volunteer information for hunts
<script>
var cooks = existing_cooks;
var hunt_guides = existing_hgs;
var gen_support = existing_gss;
console.log(cooks);
console.log(hunt_guides);
console.log(gen_support);
//Cooks multiSelect
$(".vCooks").val(cooks);
$('.vCooks').multiselect({
columns: 2,
placeholder: 'Select Cooks'
});
//Hunt Guide multi-select
$(".vHg").val(hunt_guides);
$('.vHg').multiselect({
columns: 2,
placeholder: 'Select Hunt Guides'
});
//General Support multi-select
$(".vSupp").val(gen_support);
$('.vSupp').multiselect({
columns: 2,
placeholder: 'Select General Support'
});
return false;
</script>

Get value from Select Box on change

Im trying to retrieve the value from a select box after the selected index has been changed. I keep getting an undefined index variable.
The form reloads the page so that I can update a table elsewhere on the page. The options are filled from the results of an SQL query.
The select box code.
<form action="" method="post">
<label>Select School</label>
<select class="form-control" name="schoolSelect" onchange="this.form.submit()">
<?php
foreach ($faculty as $key) { ?>
<option value="<?php echo $key['1']; ?>"><?php echo $key['1']; ?></option>
<?php } ?>
</select>
</form>
PHP used to retrive value
if (isset($_POST['schoolSelect'])){
$selectedSchool = $_POST['schoolSelect'];
$result = executeUserSelect($sqlUserBySchool, $db, $_POST['schoolSelect']);
}
EDIT
var dump =
array (size=1)
'schoolSelect' => string 'Plymouth Business School' (length=24)
Select box text = Plymouth Business School
Thanks in advance
Tony
<body>
<?php
if (isset($_POST['schoolSelect'])){
$selectedSchool = $_POST['schoolSelect'];
echo $selectedSchool;
}
else {
?>
<form action="" method="post">
<label>Select School</label>
<select class="form-control" name="schoolSelect" onchange="this.form.submit()">
<?php
foreach ($faculty as $key) { ?>
<option value="<?php echo $key['1']; ?>"><?php echo $key['1']; ?></option>
<?php } ?>
</select>
</form>
<?php } ?>
</body>

Get value from <select> in html

So I'm trying to get my value from a SELECT tag in HTML, I'm working with the POST method. Somehow when I get my answer back I only get my label, instead of getting my value which is what I need. I manage my form in 3 diferent documents,
here is my php doc, the visual part
<form action="actions_admin/demografica_asig.php" method="POST">
<div class="large-4 columns">
<label>Seleccione Periodo:
<select name="selec_periodo">
<option value="1">I</option>
<option value="2">II</option>
<option value="3">III</option>
<option vslue="4">IV</option>
</select>
</label>
</div>
</form>
my accion docmuent:
<?php
require_once("../../clases/demoasig.class.php");
$selec_periodo = $_POST['selec_periodo'];
$demoasig = new Demografica();
$demoasig->selec_periodo = $selec_periodo;
$resultdatos = $demoasig->demo_asig();
echo $resultdatos;
?>
my Class Document:
<?php
require_once('conexion.class.php');
class Demografica{
public $selec_periodo;
public function __construct(){
$this->asig = array();
}
public function demo_asig(){
$sql= "SELECT COUNT(*) FROM est_asig WHERE est_asig_trimestre={$this->selec_periodo}";
$resultado = mysql_query($sql, Conectar::conexion()) or die($sql);
$this->asig[]= $resultado;
return $this->asig;
}
}
?>

Categories