passing to model through controller in codeigniter? - php

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.

Related

get option values from database codeigniter

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>

How to pass a variable from model to controller in codeigniter

How can I pass a variable from the model to the controller?
Here is my model:
public function edititem($id){
$query = $this->db->query('SELECT * FROM tblitem WHERE item_id = "$id"');
foreach ($query->result() as $row){
$name = $row->item_name;
$description = $row->item_description;
$price = $row->item_price;
}
And here is my controller
public function editItem(){
$this->load->helper('form');
$this->load->model('ItemModel');
$this->ItemModel->edititem($this->input->get('id'));
$name = $this->input->post('name');
$description = $this->input->post('description');
$price = $this->input->post('price');
$data['items'] = $this->ItemModel->itemlist();
$this->load->view('item/item_edit',$data);
}
In which when the user clicks "Edit Item", it will populate the form with the selected row.
<form action="<?php echo base_url().'item/edititem' ?> " method="post">
<div class="form-group">
<label for="name">Name</label>
<input type="name" class="form-control" id="name" name="name" placeholder="Name" value="<?php echo set_value('name'); ?>">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" rows="3" name="description"><?php echo set_value('description'); ?></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="price">Amount (in pesos)</label>
<div class="input-group">
<div class="input-group-addon">Php</div>
<input type="text" class="form-control" name="price" id="price" placeholder="Amount" value="<?php echo set_value('price'); ?>">
<div class="input-group-addon">.00</div>
</div>
</div>
<button type="submit" class="btn btn-primary">EDIT ITEM</button>
</form>
If it is from model to controller, You can make an array and store that 3 fields. (I assume there is only single row returned by your query since you are using id as where).
$result = array();
foreach ($query->result() as $row)
{
$result['name'] = $row->item_name;
$result['description'] = $row->item_description;
$result['price'] = $row->item_price;
}
return $result;
You can access it in the controller using:
$data['items']['name'];
$data['items']['description']
$data['items']['price']
Or in your view as
$items['name'];
$items['description'];
$items['price'];
Here your model looks like this
public function edititem($id){
$query = $this->db->query('SELECT * FROM tblitem WHERE item_id = "$id"');
if ($query->num_rows() > 0) {
$row = $query->row_array(); // row_array return single row and result_array return multiple row
return $row['dt'];
And your controller looks like this
public function editItem(){
$this->load->helper('form');
$this->load->model('ItemModel');
$item_details=$this->ItemModel->edititem($this->input->get('id'));
here you use foreach loop
foreach ($item_details as $key=>$value){
//do this in $data array
} //now you can use the specific data to your view.
$this->load->view('item/item_edit',$data);
}
Your Model:
This may useful if your want to return a specific 1 row without using result()
public function edititem($id){
$this->db->select('*');
$this->db->from('tblitem ');
$this->db->where('item_id ',$id);
return $query = $this->db->get()->custom_row_object(0, 'ItemModel');
}
Your Controller: Call the edititem($id) from ItemModel (your model)
public function editItem(){
$item_id=$this->uri->segment(3); //added this
$this->load->helper('form');
$this->load->model('ItemModel');
$item_details=$this->ItemModel->edititem($item_id); //added this
$data['item_name'] = $item_details->name;
$data['item_desc'] = $item_details->description;
$data['item_price'] = $item_details->price;
//now you can use the specific data to your view.
$this->load->view('item/item_edit',$data);
}
In your view, you can use the variable like:
$item_name;
$item_desc;
$item_price;
eg:
<input type="text" name="item_name" value="<?php echo $item_name;?>" />

How do i retrieve the value of dropdown when editing in codeigniter

OK, so I have looked everywhere for a solution to my problem but found none so far.My code looks like this.I have created a dynamic view page in which edit and add views are loaded dynamically.But the problem arises when i try to retain the value of select dropdown during editing.I would be grateful if someone could help me out.
View
<div class="panel-body">
<div class="row">
<div class="col-lg-6">
<?php if(#$patient_info){
echo '<h1 class="page-header">Edit Patient</h1>';
}else{
echo '<h1 class="page-header">Add Patient</h1>';
}
?>
<?php if($this->session->flashdata('error')){ ?>
<div class="alert alert-danger"><?php echo $this->session->flashdata('error'); ?></div>
<?php } ?>
<?php if($this->session->flashdata('erroredit')){ ?>
<div class="alert alert-danger"><?php echo $this->session->flashdata('erroredit'); ?></div>
<?php } ?>
<?php //echo validation_errors('<div class="alert alert-danger">','</div>'); ?>
<form role="form" method="post" action="<?php echo isset($patient_info) ? site_url('home/patient/edit') .'/' .$patient_info->patientID : site_url('home/patient/new'); ?>">
<div class="form-group">
<?php echo form_error('pname', '<div class="alert alert-danger">', '</div>'); ?>
<label for="pname">Patient Name</label>
<input class="form-control" placeholder="Enter Patient Name" name="pname" value="<?php echo isset($patient_info) ? $patient_info->patientName : ''; ?>">
</div>
<!-- Dropdown menu for selecting clinic -->
<div class="form-group">
<label for="select">Select Clinic Name</label>
<select class="form-control" name="selectClinic">
<option value="none">Select Clinic Below</option>
<?php foreach($allclinic as $key=>$clinic){ ?>
<!--<?php //foreach($clinicByPatient as $clin): ?>-->
<option value="<?php $clinic->clinicID; ?>"
<?php if(isset($patient_info)){
echo 'selected="selected"';
}
?>
>
<?php echo $clinic->clinicName; ?>
</option>
<?php //endforeach; ?>
<?php } ?>
</select>
</div>
<!-- Select Clinic ends-->
<div class="form-group">
<label for="select">Select Dentist</label>
<select class="form-control" name="selectDentist">
<option value="">Select Dentist</option>
<?php foreach($dentistdet as $key=>$dentist){ ?>
<option value="<?php echo $did = $dentist->dentistID;?>"><?php echo $dentist->dentistName; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-lg btn-block" name="submit" value="<?php echo isset($patient_info) ? 'Update Patient' : 'Add Patient'; ?>" >
</div>
</form>
<div class="form-group">
<input type="submit" class="btn btn-danger btn-lg btn-block" value="Cancel">
</div>
Edit controller
public function edit(){
$id = $this->uri->segment(4);
$this->load->library('form_validation');
$this->load->model('clinic_model');
$this->load->model('dentist_model');
$data['patient_info'] = $this->patient_model->getPatientById($id);
$data['clinicByPatient'] = $this->patient_model->getPatientByClinic();
$data['allclinic'] = $this->clinic_model->getAllClinics();
// $data['clinicdet'] = $this->patient_model->getPatientByClinic();
if($_POST){
$this->form_validation->set_rules('pname', 'Patient Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('paddress', 'Patient Address', 'trim|required|xss_clean');
$this->form_validation->set_rules('pcontact', 'Patient Contact', 'trim|required|xss_clean');
if($this->form_validation->run()== FALSE){
$data['subview'] = 'patient/patient_new';
$this->load->view('includes/layout', $data);
}else{
$patientname = $this->input->post('pname');
$patientaddress = $this->input->post('paddress');
$patientcontact = $this->input->post('pcontact');
$select = $this->input->post('selectClinic');
$option = $this->input->post('selectDentist');
$edited = $this->patient_model->editpatient($id, $patientname, $patientaddress, $patientcontact, $select, $option);
if($edited){
$this->session->set_flashdata('successedit', 'Successfully updated the record');
redirect('home/patient');
}
}
}else{
$data['subview'] = 'patient/patient_new';
$this->load->view('includes/layout',$data);
}
}
Model looks like this
<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
class Patient_model extends CI_Model{
public function countPatients(){
$countPatient = $this->db->count_all('patient');
return $countPatient;
}
public function getallpatients(){
$query = $this->db->get('patient');
if($query->num_rows()>0){
return $query->result();
}
else{
return FALSE;
}
}//getallpatients function ends
public function getPatientByClinic(){
$this->db->select('*');
$this->db->from('patient');
$this->db->join('clinic', 'patient.clinicID = clinic.clinicID', 'left');
$this->db->join('dentist', 'patient.dentistID = dentist.dentistID', 'left');
$query = $this->db->get();
if($query->num_rows>0){
return $query->result();
}
}
public function addPatientByClinic($patientname, $patientadd, $patientcontact, $select, $option){
$data = array(
'patientName' => $patientname,
'patientAddress' => $patientadd,
'patientContact' => $patientcontact,
'clinicID' => $select,
'dentistID' => $option
);
return $this->db->insert('patient',$data);
}// method ends
public function deletePatient($id){
$verifyID = array('patientID' => $id);
// $affRows = $this->db->affected_rows();
// $obj = new Patient_model;
if($verifyID){
$this->db->where($verifyID);
$this->db->delete('patient');
if($this->db->affected_rows()){
return TRUE;
}
}
}
public function editpatient($id, $patientname, $patientaddress, $patientcontact, $select, $option){
$data = array(
'patientName' => $patientname,
'patientAddress' => $patientaddress,
'patientContact' => $patientcontact,
'clinicID' => $select,
'dentistID' => $option
);
$query = $this->db->where('patientID', $id)
->update('patient', $data);
if($query){
return true;
}
}//method ends
public function getPatientById($id){
$query = $this->db->where('patientID', $id)
->get('patient');
return $query->row();
}
}//class ends
?>
In the code for your select box, you aren't actually echoing $clinic->clinicID. Thus, when the form is submitted, the value will be empty.
You also need to be careful with how you are choosing which select element will be selected by default - you aren't comparing with anything that will change within the loop. Should you be checking against $clinic->clinicID?

Codeigniter search engine system using multi filter keyword

I'm building my own book library management system using Codeigniter. I get stuck when I want to buil search engine using filtered keyword. I have four tables (books, publisher, category, format) and I use join to retrieve data. But the results were not what I excepted. Below I show my codes:
// TABLE STRUCTURE
Books |book_id, publisher_id, cat_id, format_id, title, author, ... etc|
Publisher |publisher_id, publisher, address|
Category |cat_id, category, description|
Format |format_id, format|
// MODEL
public function findBooks ( $keyword, $publisher, $category, $format, $offset, $limit )
{
$this->db->select('*');
$this->db->join('publisher as p', 'b.publisher_id=p.publisher_id', 'left');
$this->db->join('category as c', 'b.cat_id=c.cat_id', 'left');
$this->db->join('format as f', 'b.format_id=f.format_id', 'left');
if(!empty($keyword)) {
$this->db->like('b.title', $keyword);
$this->db->like('p.publisher', $publisher);
$this->db->or_like('c.category', $category);
$this->db->or_like('f.format', $format);
}
$this->db->order_by('book_id', 'ASC');
$getData = $this->db->get('books as b', $offset, $limit);
if($getData->num_rows() > 0)
{
return $getData->result();
} else {
return NULL;
}
}
public function getPublishers()
{
$query = $this->db->query("SELECT * FROM publisher ORDER BY publisher_id ASC");
return $query;
}
public function getCategories()
{
$query = $this->db->query("SELECT * FROM category ORDER BY cat_id ASC");
return $query;
}
public function getFormat()
{
$query = $this->db->query("SELECT * FROM format ORDER BY format_id ASC");
return $query;
}
// BOOKS CONTROLLER
public function find($keyword='', $offset = '', $limit = 3;)
{
if($this->uri->segment(3) === FALSE){
$offset = 0;
}else{
$offset = ($this->uri->segment(3)-1) * $limit;
}
$keyword = mysql_real_escape_string($this->input->post('term'));
$publisher = $this->input->post('publisher_id');
$category = $this->input->post('cat_id');
$format = $this->input->post('format_id');
$check = $this->adminModel->findBooks( $keyword, $publisher, $category, $format, $offset, $limit );
if($check)
{
$data['message'] = "";
$data['res'] = $check;
$this->load->view('search_result', $data);
} else {
$data['message'] = "<div class='alert alert-warning'>No result. Please try with another keyword.</div>";
$this->load->view('search_result', $data);
}
}
// FORM VIEW
<div>
<h4>Find Books</h4>
<form action="<?php base_url(); ?>books/find" method="POST" class="form-horizontal" role="form">
<div class="input-group input-group col-md-12">
<label for="term" class="sr-only"></label>
<input type="text" class="form-control" name="term" placeholder="Enter Keyword">
</div>
<div class="input-group col-md-12">
<label for="publisher">By Publisher</label>
<select name="publisher" id="publisher" class="form-control">
<option value="0">All</option>
<?php foreach ($pub->result() as $p) { ?>
<option value="<?php echo $p->publisher_id; ?>"<?php echo set_select('publisher_id', $p->publisher_id, (!empty($data) && $data == $p->publisher_id ? TRUE : FALSE )); ?>><?php echo ucwords($p->publisher); ?></option>
<?php ; } ?>
</select>
</div>
<div class="input-group col-md-12">
<label for="category">By Category</label>
<select name="category" id="category" class="form-control">
<option value="0">All</option>
<?php foreach($cats->result() as $cat){ ?>
<option value="<?php echo $cat->cat_id; ?>"<?php echo set_select('cat_id', $cat->cat_id, (!empty($data) && $data == $cat->cat_id ? TRUE : FALSE )); ?>><?php echo ucwords($cat->category); ?></option>
<?php } ?>
</select>
</div>
<div class="input-group col-md-12">
<label for="format">By Format</label>
<select name="format" id="format" class="form-control">
<option value="0">All</option>
<?php foreach ($format->result() as $frm) { ?>
<option value="<?php echo $frm->format_id; ?>"><?php echo set_select('format', $frm->format_id, (!empty($data) && $data == $frm->format_id ? TRUE : FALSE )); ?><?php echo ucwords($frm->format); ?></option>
<?php ; } ?>
</select>
</div>
<div class="input-group col-md-12">
<button type="submit" class="btn btn-success">FIND</button>
</div>
</form>
</div>
Here what I except is, for instance, I search term "Adam" and it might be a name of person, publisher, or part of title. So, if I search the keyword "Adam" and filtered ONLY by publisher, it will show result such as Adam Publishing rather than "History of Adam and Eve" (as book title).
Another question, am I getting wrong in my code? If so, give me direction what it should be.
Best regards

How to search record from db by selecting search category in codeigniter?

I have list of record in my index page. Now i want to search a particular record/records by choosing the category (e.g phone No, email etc).How can i do this? help..
Here is my view:
<?php
$attributes = array('class'=>'searchform', 'id'=>'searchform');
echo form_open('crud/searchCrud', $attributes);?>
<div class="formelements">
<div class="formlbl">
Search:
</div>
<div class="forminput">
<input type="text" name="searchon" id ="searchon"/>
</div>
<div class="searchtyp">
<select class="searchby" name="searchby">
<option value="0">---Select--- </option>
<option value="name">Name</option>
<option value="email">Email</option>
<option value="phone">Phone</option>
</select>
</div>
<div class="searchinput">
<input type="submit" name="search" value="Search" />
</div>
</div>
<?php echo form_close();?>
Here is My controller:
public function searchCrud()
{
$records = $this->crud_mdl->searchCrud();
foreach ($records as $record) {
echo $record->name;
}
}
Here is My Model:
public function searchCrud()
{
$searchby = $this->input->post('searchby');
$searchon = $this->input->post('searchon');
$this->db->get('test')->result();
return $this->db->like($searchon, $searchby);
}
1) You should never access POST data directly in the Model.
2) Always collect them in Controller and then pass it to the Model.
3) Also always try to create your Model functions, re-usable.
Modified your code a bit. Try running it.
Controller:
public function searchCrud()
{
$searchby = $this->input->post('searchby');
$searchon = $this->input->post('searchon');
$records = $this->crud_mdl->searchCrud($searchby, $searchon);
foreach ($records as $record)
{
echo $record->name;
}
}
Model:
public function searchCrud($searchby, $searchon)
{
$this->db->like($searchon, $searchby);
$query = $this->db->get('test');
if($query->num_rows() > 0)
return $query->result();
else
return FALSE;
}

Categories