get option values from database codeigniter - php

I have a php form where I want to select options for a field Email from a list of values saved in a table emailaddress in the database. The table emailaddress has 2 fields 1. idemailaddress and 2. emailaddress, but I am still getting error trying to pull data, please help
Agreement_ctrl
$data['department_list'] = $this->Main_model->get_department_list();
$data['unit_list'] = $this->Main_model->get_unit_list();
$data['terms'] = $this->Main_model->get_terms_list();
$data['emailaddress_list'] = $this->Main_model->get_emailaddress_list();
$data['managers_list'] = $this->Main_model->get_managers_list();
$data['mtnlocation_list'] = $this->Main_model->get_mtnlocation_list();
$data['institution_list'] = $this->Main_model->get_institution_list();
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'alpha|xss_clean');
$this->form_validation->set_rules('department', 'Department');
$this->form_validation->set_rules('unit', 'Unit', 'numeric|xss_clean');
Main Model File
}
function get_emailaddress_list()
{
$this->db->order_by('emailaddress', 'ASC');
$query = $this->db->get('emailaddress');
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$result [$row->id] = $row;
}
return $result;
}else{
return FALSE;
}
}
Form Page
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="Email">Email Address:</label>
<div class="col-sm-9">
<select name="Email" class="Email form-control" id="Email">
<option value="" <?php echo set_select('Email', ''); ?> >-Select-</option>
<?php if($emailaddress_list){
foreach($emailadress_list as $emailaddress){ ?>
<option value="<?php echo $emailadress->idemailaddress?>" <?php echo set_select('Email', $emailaddress->idemailaddress); ?>><?php echo $emailaddress->emailaddress?></option>
<?php }
}?>
</select>
</div>
</div>

You don't need the foreach loop in your model, just return the query result.
function get_emailaddress_list(){
$this->db->order_by('emailaddress', 'ASC');
$query = $this->db->get('emailaddress');
$data = ($query->num_rows())? $query->result():false;
return $data;
}
Then you loop through this results in your view to create the select options:
<select name="Email" class="Email form-control" id="Email">
<?php if($emailaddress_list):?>
<option value="" disabled selected>-Select-</option>
<?php foreach($emailadress_list as $row): ?>
<option value="<?=$row->idemailaddress?>">
<?=$row->emailaddress?>
</option>
<?php endforeach;?>
<?php else:?>
no records found
<?php endif;?>
</select>

Related

how to display selected multiple dropdown values in edit page in CodeIgniter

how to display selected multiple dropdown values in edit page in CodeIgniter
Values ​​are not displaying in multiple dropdowns on the edit page
this is how to retrieve data in db
<?php $assignuserstable = $this->db->get_where('assignuserstable',array('user_id'=>$user_id))->row_array(); ?>
<div class="form-group col-md-6">
<label for="admin_id"><?php echo get_phrase('Assign User'); ?>
<span class="text-danger">*</span></label>
<select class="form-control selectpicker" name="admin_idd[]" id="admin_id"
placeholder="Assign User" required multiple>
<option value="" hidden><?php echo get_phrase('Select User'); ?></option>
<?php
$system_usertable = $this->db->get('system_usertable')->result_array();
foreach($system_usertable as $row2):
?>
<option value="<?php echo $row2['admin_id'];?>"
<?php if($assignuserstable['admin_id'] == $row2['admin_id'])echo 'selected';?>>
<?php echo $row2['first_name'];?>
</option>
<?php
endforeach;
?>
</select>
</div>
This is how multiple array is added to the database
model
public function addclientdetails(){
$data['business_name'] = html_escape($this->input->post('business_name'));
$data['legal_name'] = html_escape($this->input->post('legal_name'));
$data['status'] = html_escape($this->input->post('status'));
$data['rating'] = html_escape($this->input->post('rating'));
$data['SU_id'] =html_escape($this->input->post('admin_id'));
date_default_timezone_set("Asia/Kolkata");
$data['created_at'] = Date('Y-m-d h:i:s');
$data['created_by'] = $this->session->userdata('admin_id');
$this->db->insert('user_table', $data);
$insertId = $this->db->insert_id
$admin_idd =html_escape($this->input->post('admin_idd'));
$result = array();
foreach($admin_idd AS $key => $val){
$result[] = array(
'user_id' => $insertId,
'admin_id' => $_POST['admin_idd'][$key],
'user_type' => html_escape($this->input->post('user_type')),
);
}
$this->db->insert_batch('assignuserstable', $result);
$insertId = $this->db->insert_id();
return $insertId;
}
it is impossible to identify the problem when you don't share your code. Please share your model and controller too.
At first please echo $system_usertable and $row2 and check whether there is a data or not.
and your option should looks like this
<option value="<?php echo $row2['admin_id'];?>" <?php echo (isset($assignuserstable['admin_id']) && $assignuserstable['admin_id'] == $row2['admin_id'])? 'selected' : NULL; ?>><?php echo $row2['first_name'];?></option>

How to Save the Checkbox Value Form to MySQL in One Field

How to Save the Checkbox Value Form to MySQL in One Field, can anyone help me..
Here is my code:
function student($param1 = '') {
if ($this->session->userdata('admin_login') != 1) {
redirect('login', 'refresh');
}
$running_year = $this->db->get_where('settings' , array('type' => 'running_year'))->row()->description;
if ($param1 == 'create') {
$data['ekskul_id'] = $this->input->post('ekskul_id');
$this->db->insert('student', $data);
}
}
this is my display code
<div class="form-group">
<label for="field-2" class="col-sm-3 control-label">Ekstrakurikuler</label>
<div class="col-sm-5">
<select data-placeholder="Select" name="ekskul_id[]" multiple class="chosen-select" tabindex="8">
<?php
$ekstra = $this->db->get('ekstrakurikuler')->result_array();
foreach($ekstra as $row):
?>
<option value="<?php echo $row['ekskul_id'];?>"><?php echo $row['ekskul_name'];?></option>
<?php
endforeach;
?>
</select>
</div>
</div>
use below code to store multiple id in one field:
<?php
$ekskul_id= implode(",",$_POST['ekskul_id']);
?>
In your code :
if(isset($this->input->post('ekskul_id'))){
$data['ekskul_id'] = implode(",",$this->input->post('ekskul_id'));
}

How to read value in combobox when editing data with codeigniter

I can't show the data that I want to edit from my table. The combobox and the table don't show data when I edit the data categories, sub-categories, and manufacturers. I want to be able to see the data from my table after editing.
Controller form
public function data_items_edit($id)
{
$this->load->model('additem_m');
$model3 = $this->additem_m;
$data['table'] = $model3->get_where2($id)[0];
//$data['table'] = $model3->get();
$this->load->model('category_m');
$model = $this->category_m;
$data['category'] = $model->get();
$this->load->model('subcategory_m');
$model1 = $this->subcategory_m;
$data['sub'] = $model1->get();
$this->load->model('manufactures_m');
$model2 = $this->manufactures_m;
$data['manu'] = $model2->get();
//print_r($data['table']);
$this->load->view('items/edit_items_v', $data);
}
Data table controller
public function index()
{
if($this->session->has_userdata('isLogin')){
$this->load->model('additem_m');
$model = $this->additem_m;
$data['table'] = $model->get('items.*, item_categories.name as ic,
item_categories_sub.name as ics, item_manufactures.name as im',
[
['table'=>'item_categories','condition'=>'item_categories.id =
items.item_category_id'],
['table'=>'item_categories_sub','condition'=>'item_categories_sub.id
= items.item_category_sub_id'],
['table'=>'item_manufactures','condition'=>'item_manufactures.id =
items.item_manufacturer_id'],
]);
//print_r($data['table']);
$this->load->view('items/items_v', $data);
}else{
redirect('login');
}
}
View Form
<div class="form-group">
<label class="col-sm-4 control-label form-label">Category :</label>
<div class="col-sm-8">
<select name="item_category_id" class="form-control" id="category">
<option value='' <?php if($category == '0'){ echo 'selected';} ?>>--Select--</option>
<?php foreach($category as $category){
echo '<option value="'.$category->id.'">'.$category->name.'</option>';
} ?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label form-label">Sub Category</label>
<div class="col-sm-8">
<select name="item_category_sub_id" class="form-control" id="category_sub">
<option value=''>- Select Sub Category -</option>
</select>
</div>
</div>
<div class="rightcontact">
<div class="form-group">
<label class="col-sm-4 control-label form-label">Manufacturer</label>
<div class="col-sm-8">
<select name="item_manufacturer_id" class="form-control" id="item_manufacturer_id">
<option>- Select Manufacturer -</option>
<?php foreach($manu as $manu){
echo '<option value="'.$manu->id.'">'.$manu->name."</option>";
} ?>
</select>
</div>
</div>
</div>
My view
You have to add selected attribute to the options.
$category == $category->id ? "selected" : ""
Something like this
<?php
foreach($category as $category){
echo '<option value="'.$category->id.'" '. $category == $category->id ? "selected" : "" .'>'.$category->name.'</option>';
^ ^
}
?>

How to avoid a repetitive code when creating similar dropdown lists?

Below is the code where i created a drop down list, i am able to retrieve data from MySQL but i have to repeat the option step for every field, how can I setup a code for the drop down so i can just shorten to call it once in selection list, like in a for loop..also how do i create a error message to display if there is no selection, and if i select a data from the list it stores in the database
<form action="sign.php" method="post">
<label for="employee_name">Employee name</label>
<select name = "employee_name">
<option value=""> -----------Select----------- </option>
<?php
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
<label for="manager">manager</label>
<select name = "manager">
<option value=""> -----------Select----------- </option>
<?php
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
<label for="senior">Senior</label>
<select name = "Senior">
<option value=""> -----------Select----------- </option>
<?php
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
<input type="submit" name="register" value=" Click to Add"></button>
</form>
Use array and run query once to set options in array.
<?php
$optionArray = array();
$stmt = $pdo->prepare('Select name from people');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$optionArray[] = '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
?>
<form action="sign.php" method="post">
<label for="employee_name">Employee name</label>
<select name = "employee_name">
<option value=""> -----------Select----------- </option>
<?php
foreach($optionArray as $row)
{
echo $row;
}
?>
</select>
how can I setup a code for the drop down so i can just shorten to call it once in selection list, like in a for loop.
Just create a loop. though it should be foreach, not for.
First collect your data,
$people = $pdo->query('Select name from people order by name')->fetchAll(PDO::FETCH_COLUMN);
$sections = [
'employee_name' => 'Employee name',
'manager' => 'Manager',
'senior' => 'Senior',
];
and then loop it over
<form action="sign.php" method="post">
<?php foreach ($sections as $label => $caption): ?>
<label for="<?=$label?>"><?=$caption?></label>
<select name = "<?=$label?>">
<option value=""> -----------Select----------- </option>
<?php foreach ($people as $name): ?>
<option><?=$name?></option>
<?php endforeach ?>
</select>
<?php endforeach ?>
<input type="submit" name="register" value=" Click to Add"></button>
</form>
Instead of repeating this every time you can create a method which performs the same task.
<label for="employee_name">Employee name</label>
<select name = "employee_name">
<option value=""> -----------Select----------- </option>
<?=loadOptions('name','people');?> <!--shortcut way to echo in php-->
</select>
<?php
function loadOptions($field,$table){
$stmt = $pdo->prepare('Select '.$field.' from '.$table);
$stmt->execute();
$options='';
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$options .= '<option>'.$row['name'].'</option>';
}
return $options;
}
?>

passing to model through controller in codeigniter?

I want to select an option of product categories from dropdown menu and show products that have that specific category.
Here is the form part from my view:
<?php $attributes = array('method'=>"POST", "class" => "myc", "id" => "myc", "name" => "dropdwn");
echo form_open_multipart('frontend/home/display', $attributes); ?>
<div class="form-group">
<div class="col-sm-9">
<select class="form-control" name="category" onchange="this.form.submit();" />
<option value="" <?php echo set_select('category', 'zero', TRUE); ?>>Categories...</option>
<option value="phone" >Phones</option>
<option value="laptops">Laptops</option>
<option value="accessories" >Accessories</option>
</select>
</div>
</div>
<?php echo form_close(); ?>
As you can see I get the option from dropdown through onchange="this.form.submit();
(if it's not a good idea please suggest other way to do, I just didn't want to use ajax, as I'm not so good at it yet, anyhow suggest what seems better).
Then in my controller I get the option and convert it to array, to use it in my model.
controller part:
public function display($sort_by='product_id', $sort_order='asc', $offset = 0)
{
$this->load->model('model_product');
$selected = implode(" ", $this->input->post());
//var_dump($selected);
$results = $this->model_product->fetch($selected, $limit, $offset, $sort_by, $sort_order);
$data['products'] = $results['rows'];
$data['num_results'] = $results['num_rows'];
//and then goes pagination part, I guess no meaning posting it, as it works fine.
}
My model:
function fetch($selected, $limit, $offset, $sort_by, $sort_order)
{
$sort_order = ($sort_order == 'desc') ? 'desc' : 'asc';
$sort_columns = array('product_id', 'name', 'description', 'category', 'country', 'price');
$sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'product_id';
//actual results query
$q = $this->db->select('product_id, name, description, category, country, price, img_name, thumb_name')
->from('products')
->where('category', $selected)
->limit($limit, $offset)
->order_by($sort_by, $sort_order);
$ret['rows'] = $q->get()->result();
var_dump($ret['rows']);
die;
//count query
$q = $this->db->select('COUNT(*) as count', FALSE)
->from('products');
$tmp = $q->get()->result();
$ret['num_rows'] = $tmp[0]->count;
return $ret;
}
Here I get no results, probobly because where clause returns no result.
However if I change the where clause such as ->where('category', 'phones') it shows only phones. So how can I pass selected value to the query correctly?
i wil help you.
View file
<div class="box-header">
<h3 class="box-title">Enter Category Details</h3>
</div>
<?php
echo validation_errors(); $attributes = array('id' => 'formCategory','name'=>'formCategory');
?>
<?php echo form_open_multipart(base_url().'moderator/B2BCategory/addcategory'); ?>
<div class="box-body">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="txtcatname">Title of Category :</label>
<input type="text" name="txtcatname" class="form-control" id="txtcatname" placeholder="Category Name " required="required">
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="categorysection">Section of the Category :</label>
<select class="form-control" name="categorysection" required>
<option value="" >----Select------</option>
<option value="1">Laptop</option>
<option value="2">Phone</option>
<option value="3">Accessories</option>
</select>
<input type="submit" name="selsub" class="btn btn-primary">
</div>
</div>
</div>
Controller
public function addcategory() {
$this->load->helper(array('form', 'url'));
$this->load->view('moderator/templates/header');
$this->load->view('moderator/templates/sidebar');
if ($this->input->post('selsub')) {
$data = array('ctg_name' => $this->input->post('categorysection'));
$this->b2bcategory_model->form_insert($data);
}
In Model
public function form_insert($data){
$this->db->insert('jil_category', $data);
}
To display output from table,just use
public function viewall()
{
$this->db -> select('*');
$this -> db -> from('jil_category');
$query = $this -> db -> get();
return $query->result();
}
From
$selected = implode(" ", $this->input->post());
To
$selected = $this->input->post('category');
By the way, echo & var_dump() would be very useful in debugging your controller and/or model.

Categories