I'm having difficulty with display data from the db to dropdown.
This is what I have tried:
Model.php
public function __construct()
{
parent::__construct();
}
function getAllGroups()
{
/*
$query = $this->db->get('location');
foreach ($query->result() as $row)
{
echo $row->description;
}*/
$query = $this->db->query('SELECT description FROM location');
foreach ($query->result() as $row)
{
echo $row->description;
}
//echo 'Total Results: ' . $query->num_rows();
}
Controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Delivery_controller extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('delivery_model');
}
public function index()
{
$data['title']= 'Warehouse - Delivery';
$this->load->view('include/header',$data);
$this->load->view('include/navbar',$data);
$this->load->view('delivery_view', $data);
$this->load->view('include/sidebar',$data);
$this->load->view('include/footer',$data);
$data['groups'] = $this->delivery_model->getAllGroups();
}
}
View.php
<select class="form-control">
<?php
$data = $this->delivery_model->getAllGroups();
foreach($description as $each)
{ ?><option value="<?php echo $each['description']; ?>"><?php echo $each['description']; ?></option>';
<?php }
?>
</select>
But the results appear on top of my page. It's not appearing on the dropdown list. What am I doing wrong in here? Help is pretty much appreciated. Thanks.
You should not be calling your model from your view. Instead try calling you model and setting $data['groups'] before you load your views.
Also do not echo the row results in your model unless you want it displayed on your page.
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Delivery_controller extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('delivery_model');
}
public function index()
{
$data['title']= 'Warehouse - Delivery';
$data['groups'] = $this->delivery_model->getAllGroups();
$this->load->view('include/header',$data);
$this->load->view('include/navbar',$data);
$this->load->view('delivery_view', $data);
$this->load->view('include/sidebar',$data);
$this->load->view('include/footer',$data);
}
}
Model:
public function __construct()
{
parent::__construct();
}
function getAllGroups()
{
/*
$query = $this->db->get('location');
foreach ($query->result() as $row)
{
echo $row->description;
}*/
$query = $this->db->query('SELECT description FROM location');
return $query->result();
//echo 'Total Results: ' . $query->num_rows();
}
View:
<select class="form-control">
<?php
foreach($groups as $row)
{
echo '<option value="'.$row->description.'">'.$row->description.'</option>';
}
?>
</select>
This is what you should do:
Model:
public function __construct()
{
parent::__construct();
}
function getAllGroups()
{
$query = $this->db->query('SELECT description FROM location');
return $this->db->query($query)->result();
}
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Delivery_controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('delivery_model');
}
public function index()
{
$data['title']= 'Warehouse - Delivery';
$data['groups'] = $this->delivery_model->getAllGroups();
//I take here a sample view, you can put more view pages here
$this->load->view('include/header',$data);
}
}
View:
<select class="form-control">
<?php foreach($groups as $each){ ?>
<option value="<?php echo $each->description; ?>"><?php echo $each->description; ?></option>';
<?php } ?>
</select>
Codeigniter already has specialized functions that minimize the amount of html that you have to dump in your code:
Model
public function description_pulldown(){
$this->db->from('location');
$query = $this->db->get();
foreach($query->result() as $row ){
//this sets the key to equal the value so that
//the pulldown array lists the same for each
$array[$row->description] = $row->description;
}
return $array;
}
Controller
public function index(){
$data['description_list'] = $this->delivery_model->description_pulldown();
//load all of your view data
$this->load->view('delivery_view', $data);
}
View
echo form_label("Description");
echo form_dropdown('description', $description_list, set_value('description'), $description_list);
If you need to have the view pull up the previous data in the dropdown list, you can do a foreach loop to obtain the previous value of the dropdown from the database ie... $description = $item->description; and in the view, change the 'set_value('description')' to simply '$description.'
Never call a model from a view. It is doable but the again you lose the point of using an MVC in the first place.
Call the model from your controller. Get the data and pass the data in to your view.
Use like below.
public function index(){
$data['title']= 'Warehouse - Delivery';
$data['groups'] = $this->delivery_model->getAllGroups();
$this->load->view('include/header',$data);
$this->load->view('include/navbar',$data);
$this->load->view('delivery_view', $data);
$this->load->view('include/sidebar',$data);
$this->load->view('include/footer',$data);
}
In your view, simply loop around the $groups variable and echo to your dropdown.
<select class="form-control">
<?php
$i = 0;
while($i < count($groups)){
$val= $groups[$i]['value'];
$des = $groups[$i]['description'];
echo "<option value='$i'>$des</option>";
}
</select>
And your model's function should be,
function getAllGroups(){
$query = $this->db->get('location');
return $query->result_array();
}
Better I think, in your view use:
On your model get all your data in an array with:
public function get_all_description()
{
$query = $this->db->get('description');
return $query->result_array();
}
In controller:
$data['description']=$this->model->get_all_description();
In view:
for($i=0;$i<sizeof($description);$i++)
{
$description2[$description[$i]['description']]=$marque[$i]['description'];
}
echo form_dropdown('description', $description22, set_value('description'));
This is Codeigniter 4 answer.
Controller
public function index()
{
$delModel = new delivery_model();
$groups=$delModel->getAllGroups();
$data = [
'title' => 'Warehouse - Delivery',
'groups' => $groups,
];
return view('include/header',$data);
return view('include/navbar',$data);
return view('delivery_view', $data);
return view('include/sidebar',$data);
return view('include/footer',$data);
}
Model
public function getAllGroups()
{
$db = \Config\Database::connect();
$query = $db->query("SELECT description FROM location;");
return $query->getResultArray();
}
View
<select>
<?php
foreach ($groups as $row) {
echo '<option value="' . $row["description"] . '">' .$row["description"] . '</option>';
}?>
</select>
public function __construct(){
parent::__construct();
$this->load->helper('url');
$this->load->model('trip_model');
}
public function index(){
$data['trips']=$this->trip_model->get_all_trips();
$this->load->view("trip_view",$data);
}
public function trip_add(){
if(!empty($_FILES['trip_image']['name'])){
$config['upload_path'] = 'assests/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 2048;
$config['file_name'] = $_FILES['trip_image']['name'];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('trip_image')){
$uploadData = $this->upload->data();
$trip_image = $uploadData['file_name'];
}
else{
$trip_image = 'Hello..!!';
}
}
else{
$trip_image = 'Byeee..!!';
}
$data = array(
'trip_image' => $trip_image,
'name' => $this->input->post('name'),
'location' => $this->input->post('location'),
'trip_datetime' => $this->input->post('trip_datetime')
);
$insert = $this->trip_model->trip_add($data);
echo json_encode(array("status" => TRUE));
}
function do_upload(){
$url = "assests/images/";
$image = basename($_FILES['trip_image']['name']);
$image = str_replace(' ','|',$image);
$type = explode(".",$image);
$type = $type[count($type)-1];
if (in_array($type,array('jpg','jpeg','png','gif'))){
$tmppath="assests/images/".uniqid(rand()).".".$type;
if(is_uploaded_file($_FILES["trip_image"]["tmp_name"])){
move_uploaded_file($_FILES['trip_image']['tmp_name'],$tmppath);
return $tmppath;
}
}
}
public function ajax_edit($id){
$data = $this->trip_model->get_by_id($id);
echo json_encode($data);
}
public function trip_update(){
if(!empty($_FILES['trip_image']['name'])){
$config['upload_path'] = 'assests/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['trip_image']['name'];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->upload_img('trip_image')){
$uploadData = $this->upload->data();
$trip_image = $uploadData['file_name'];
}
else{
$trip_image = 'Hello..!!';
}
}
else{
$trip_image = 'Byeee..!!';
}
$data = array(
'trip_image' => $trip_image,
'name' => $this->input->post('name'),
'location' => $this->input->post('location'),
'trip_datetime' => $this->input->post('trip_datetime')
);
$this->trip_model->trip_update(array('trip_id' => $this->input->post('trip_id')), $data);
echo json_encode(array("status" => TRUE));
}
public function trip_delete($id){
$this->trip_model->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
}
Related
I have the following code that query the database and display it in view.
However, I am getting these error:
- Message: Undefined variable: portfolio Filename: portfolio/home.php
- Message: Invalid argument supplied for foreach() Filename: portfolio/home.php
How should I resolve the error?
Controller (Portfolio.php)
<?php
class Portfolio extends CI_Controller {
public function view($portfolio = 'home')
{
if ( ! file_exists(APPPATH.'/views/portfolio/'.$portfolio.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($portfolio); // Capitalize the first letter
$this->load->view('templates/header', $data);
$this->load->view('portfolio/'.$portfolio, $data);
$this->load->view('templates/footer', $data);
}
public function __construct()
{
parent::__construct();
$this->load->model('portfolio_model');
$this->load->helper('url_helper');
}
public function index()
{
$data['portfolio'] = $this->portfolio_model->get_portfolio();
$this->load->view('templates/header', $data);
$this->load->view('portfolio/home', $data);
$this->load->view('templates/footer');
}
}
?>
Model (Portfolio_model)
<?php
class Portfolio_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_portfolio()
{
$query = $this->db->select('title')->from('webinfo')->get();
return $query->result_array();
}
}
?>
View (home.php)
<?php foreach ($portfolio as $portfolio_item): ?>
<h3><?php echo $portfolio_item['title']; ?></h3>
<?php endforeach; ?>
routes.php
$route['portfolio/(:any)'] = 'portfolio/view/$1';
$route['portfolio'] = 'portfolio';
$route['default_controller'] = 'portfolio/view';
$route['(:any)'] = 'portfolio/view/$1';
Couple of things may work
Model
public function get_portfolio() {
$query = $this->db->get('webinfo');
if ($query->num_rows() > 0 ) {
return $query->result_array();
} else {
return FALSE;
}
}
On controller
<?php
class Portfolio extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('portfolio_model');
$this->load->helper('url');
}
public function index() {
$data['portfolio'] = array();
$results = $this->portfolio_model->get_portfolio();
// You may need to remove !
if (!isset($results) {
foreach ($results as $result) {
$data['portfolio'][] = array(
'title' => $result['title']
);
}
}
$this->load->view('templates/header', $data);
$this->load->view('portfolio/home', $data);
$this->load->view('templates/footer');
}
public function view($portfolio = 'home') {
if (!file_exists(APPPATH.'/views/portfolio/'.$portfolio.'.php')) {
show_404();
}
$data['title'] = ucfirst($portfolio); // Capitalize the first letter
$this->load->view('templates/header', $data);
$this->load->view('portfolio/'.$portfolio, $data);
$this->load->view('templates/footer', $data);
}
}
View
<?php if ($portfolio) {?>
<?php foreach ($portfolio as $portfolio_item) { ?>
<h3><?php echo $portfolio_item['title']; ?></h3>
<?php } ?>
<?php } else { ?>
<h3>No Result</h3>
<?php } ?>
I also would recommend auto loading the database
$autoload['libraries'] = array('database');
Instead of using $this->load->database();
my controller :-
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cnewincident extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function index()
{
$this->load->model('users/supervisor/Mnewincident');
$data['category'] = $this->Mnewincident->getCatgories();
//loads up the view with the query results
$this->load->view('users/supervisor/vnewincident',$data);
if($this->input->post('addrequest'))
{
$this->load->model('users/supervisor/Mnewincident');
// to get the username from table who is creating this request
$session_data = $this->session->userdata('emailid');
$firstname = $this->Mnewincident->get_firstname($session_data);
// passing that usename in newincident table
if($this->Mnewincident->add_request($firstname))
{
$this->session->set_flashdata( 'message', 'Request added successfully.' );
redirect('users/supervisor/Cnewincident');
}
else
{
$this->session->set_flashdata( 'message', 'Failed to add the request. Try again' );
redirect('users/supervisor/Cnewincident');
}
}
}
//call to fill the second dropdown with the subcategories
public function loadsubcat()
{
echo $category_id = $this->input->post('id',TRUE);
$subcatData['subcatDrop']=$this->Mnewincident->getSubcatgories($category_id);
$output = null;
foreach ($subcatData['subcatDrop'] as $row)
{
$output .= "<option value='".$row->subcategory_description."'>".$row->subcategory_description."</option>";
}
echo $output;
}
}
?>
My model :-
class Mnewincident extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function getCatgories()
{
$this->db->select('category_id,category_description');
$this->db->from('tbl_categorymaster');
$query = $this->db->get();
foreach($query->result_array() as $row)
{
$data[$row['category_id']]=$row['category_description'];
}
return $data;
}
public function getSubcatgories($category_id=string)
{
$this->db->select('srno,subcategory_description');
$this->db->from('tbl_subcategorymaster');
$this->db->where('category_id',$category_id);
$query = $this->db->get();
return $query->result();
}
}
My view code :-
$(document).ready(function() {
$("#category").change(function(){
$.ajax({
url:"<?php echo base_url()."users/supervisor/Cnewincident/loadsubcat"?>",
data: {id:$(this).val()},
type: "POST",
success:function(data){
$("#subcategory").html(data);
}
});
});
});
1.Remove the echo from loadsubcat()
public function loadsubcat()
{
**echo** $category_id = $this->input->post('id',TRUE);
..........
.................
}
Hope it works.....
Hi i am not sure why are my codes not working.
This is the Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin extends CI_Controller {
public function __construct(){
parent::__construct();
if (! $this->session->userdata('is_logged_in')){
redirect('main/restricted');
} else {
$privilege = $this->session->userdata('privilege');
if ($privilege == 'member'){
redirect('main/restricted');
}
}
}
public function index() {
$this->load->model("model_books");
$data2 = $this->model_books->select_book();
$data = array(
'title' => 'Admin Page'
);
$this->load->view("header", $data);
$this->load->view("admin", $data2);
$this->load->view("footer");
}
This is the Model:
<?php
class Model_books extends CI_Model {
public function select_book(){
$query = $this->db->get('books');
if ($query){
return $query->result();
} else {
return false;
}
}
}
This is the View:
<?php
echo $data2->content;
?>
I got around 10 books inside the database however the books in the database are not showing up.
Try this
public function index() {
$this->load->model("model_books");
$data = array(
'title' => 'Admin Page',
'books' => $this->model_books->select_book()
);
$this->load->view("header", $data);
$this->load->view("admin", $data);
$this->load->view("footer");
}
In view
<?php
print_r($books);
?>
try the following in constructor function in model
$db = $this->load->database('default', TRUE);
I trying to get Banner Images from DB via controller and model.
My controller:
class Home extends CI_Controller {
//put your code here
public function __construct() {
parent::__construct();
$this->load->model('home_model');
}
public function index() {
$data = array();
$data['bannerInfo'] = $this->home_model->selectBanner($banner_id);
$data['result'] = $this->home_model->selectCategory($category_id);
$data['banner'] = $this->load->view('banner',$data, TRUE);
$data['maincontent'] = $this->load->view('home_message',$data,TRUE);
$data['title'] = 'NZ Furniture Products ';
$data['keywords'] = 'furniture bangladesh';
$this->load->view('home', $data);
}
My model class:
class Home_Model extends CI_Model {
// put your code here
public function selectCategory($category_id)
{
$this->db->select('*');
$this->db->from('tbl_category');
$this->db->order_by("category_id", "desc");
$query_result= $this->db->get();
$results = $query_result->result();
return $results;
}
public function selectBanner($banner_id)
{
$this->db->select('*');
$this->db->from('tbl_banner');
$this->db->where('banner_id',$banner_id);
//$this->db->order_by("product_id", "desc");
$query_result = $this->db->get();
$results = $query_result->result();
return $results;
}
$
Views:
home_message:::
<?php foreach ($result as $values) { ?>
<div class="single_product">
<div class="product_image">
<img src="<?php echo base_url();?><?php echo $values->category_image ?>" />
</div>
<span class="category_title"> <?php echo $values->category_name ?> </span>
</div>
<?php } ?>
banner
<div>
<?php foreach ($bannerInfo as $values) { ?>
<?php echo $values->banner_image ?>
<?php } ?>
</div>
If you want to show all banners. You have to remove where clause. Default ordering is desc.
Controller file:
class Home extends CI_Controller
{
public function __construct() {
parent :: __construct();
$this->load->model('home_model');
}
public function index() {
$data = array();
$data['bannerInfo'] = $this->home_model->selectBanner();
$data['result'] = $this->home_model->selectCategory($category_id);
$data['banner'] = $this->load->view('banner', $data, TRUE);
$data['maincontent'] = $this->load->view('home_message', $data, TRUE);
$data['title'] = 'NZ Furniture Products ';
$data['keywords'] = 'furniture bangladesh';
$this->load->view('home', $data);
}
}
Model file:
class Home_Model extends CI_Model
{
public function selectCategory($category_id)
{
$this->db->select('*');
$this->db->from('tbl_category');
$this->db->order_by("category_id", "desc");
$query_result = $this->db->get();
$results = $query_result->result();
return $results;
}
public function selectBanner($order_by = "desc")
{
$this->db->select('*');
$this->db->from('tbl_banner');
$this->db->order_by("banner_id", $order_by);
return $this->db->get()->result();
}
}
I try add example from http://ellislab.com/codeigniter/user_guide/tutorial/news_section.html
to my site, this is code:
news_model
<?php
class News_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_news($art = FALSE)
{
if ($art === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('art' => $art));
return $query->row_array();
}
public function set_news()
{
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'art' => $art,
'text' => $this->input->post('text'),
'image'=> $image
);
return $this->db->insert('news', $data);
}
}
?>
news_controller
<?php
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}
public function index()
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$data['errors_login'] = array();
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('main/open_news', $data);
}
public function view($art) {
$data['news_item'] = $this->news_model->get_news($art);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$data['errors_login'] = array();
$this->load->view('main/open_one_news', $data);
}
}
open_news
<?php
$this->load->view('mains/header');
$this->load->view('main/news');
$this->load->view('mains/footer');
?>
news view
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
<?php echo $news_item['text'] ?>
</div>
View article
<?php endforeach ?>
And when I click in View article
The page is not forwarding to concret page with news, only in link duplicate "news":
http://localhost/index.php/news/news/news/news/news/news
I dont know what is problem. But I think it will by may in routes.config
Because I have only:
$route['default_controller'] = 'login'; -> this is my start page
But in CodeIgniter tutorial is:
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
But when I add some from 3 first line, even the first page with list of news doesn`t open.
SOLVED:
I make stupid mistake. Because controller name news, but function: public function view($art), and the link should be: 'news/view/'.$news_item['art'].
I think problem with the below link
View article
use codeigniter anchor instead
anchor('news/'.$news_item['art'],'View article');
try this and feed me back
You forgot the echo at:
View article
You should use:
View article
or:
<?php echo anchor('news/' . $news_item['art'], 'View article');
or:
<?php echo anchor("news/{$news_item['art']}", 'View article');