I'm learning CodeIgniter From this link. I've a little confusion in fetching the data from database.
<h2><?php echo $title; ?></h2>
<?php foreach ($news as $news_item): ?>
<h3><?php echo $news_item['title']; ?></h3>
<div class="main">
<?php echo $news_item['text']; ?>
</div>
<p>View article</p>
While displaying the data in view they have used a variable $news in foreach loop. However this variable is never defined anywhere
Copied from here
$query = $this->db->get('mytable');
// Produces: SELECT * FROM mytable
The second and third parameters enable you to set a limit and offset clause:
$query = $this->db->get('mytable', 10, 20);
// Produces: SELECT * FROM mytable LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
You'll notice that the above function is assigned to a variable named $query, which can be used to show the results:
$query = $this->db->get('mytable');
foreach ($query->result_array() as $row)
{
echo $row['title'];
}
Try like this hope this will give you what you want simply make a controller and call the associated model in the constructor and perform the function what your want it will return the array so you will be eassilly fetch and use it in your view.
Controller code
class TestController extends Controller{
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->model('User');
}
public function index(){
$data['all_user']=$this->User->getAllUser();
$this->load->view('index',$data);
}
}
this is my model code
class User extends CI_Model{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function getAllUser()
{
$this->db->select('*');
$this->db->from('users');
return $this->db->get()->result();
}
}
just follow the steps
make a controller
make a function inside the controller
call the associated model function into it and you will definately get the result.
Have you seen this Controller code ? (above the code that you pick, in the tutorial)
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
$news is passed through as $data element from the Controller to the View
Related
I am new to codeigniter and trying to get a percentage result outputted into the view of codeigntier for my project. Once I fix this, things will be much smoother.
He is the model function:
<?php
public function _construct()
{
$this->load->database();
}
public function percent_specilation1($numstudent)
{
$query = $this->db->query("SELECT * FROM Student WHERE Student.JRNOption ='1'");
$numstudent = $query->num_rows()/25;
if($query->num_rows() > 0){
return $numstudent;
}
return null;
}
?>
Here is the controller.
<?php
class Statscontroller extends CI_Controller {
public function _contruct(){
parent::_construct();
$this->load->model('Stats_model');
}
public function index(){
//echo "Various stats for the Journalism department:";
$data['Test'] = $this->Stats_model->percent_specilation1($numstudent);
}
public function view($page = 'Statsview')
{
if ( ! file_exists(APPPATH.'views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
//$data['title'] = ucfirst($page);
$this->load->view('templates/header',$data);
$this->load->view('Statscontroller/index',$data);
$this->load->view('templates/header');
}
?>
Here is the view
<html>
<h1> Various Statistics for the Journalism department</h1>
<?php
echo "Percent of students that are undecided:";
echo $Test; ?>
</html>
What am I doing wrong? I been trying to get it right for over an hour and I just want to output the single result from the database query. Any help you can provide would be great.. please be respectful. Thanks!
Try this code, I have updated some of code of controller and model and use primary key of student table for student_id in model query.
Update Model:
<?php
public function _construct()
{
$this->load->database();
}
public function percent_specilation1()
{
$query = $this->db->query("SELECT (SELECT COUNT(s2.student_id)
FROM Student s2
WHERE s2.JRNOption='1')*100/COUNT(s1.student_id) AS percentage
FROM Student s1");
$result = $query->row_array();
return $result['percentage'];
}
?>
Updated controller:
<?php
class Statscontroller extends CI_Controller {
public function _contruct(){
parent::_construct();
$this->load->model('Stats_model');
}
public function index(){
//echo "Various stats for the Journalism department:";
$data['Test'] = $this->Stats_model->percent_specilation1();
$this->load->view('templates/header',$data);
$this->load->view('Statscontroller/index',$data);
$this->load->view('templates/header');
}
}
?>
Hope this will help you.
I'm new in codeigniter, I'm having a challenge with num_rows on view page
Here's the sample of the code - Updated
Model
public function __construct()
{
parent::__construct();
}
public function total_referred_in()
{
$query = $this->db->query('SELECT * FROM daily_out_patient');
return $query->num_rows();
}
Controller
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('Referrals_form_model', 'referral'); /* LOADING MODEL * Referral_form_model as referral */
}
public function index()
{
$this->load->helper('url');
$this->load->view('referrals_form_view');
}
public function referral_in()
{
$data['total_referred_in'] = $this->load->referral->total_referred_in(); //get referral data
$this->load->view("referral_form_view", $data);
}
}
View
<span><?php
echo $query->num_rows();
?></span>
when i run the code, it tell me undefined variable "query"
Please help.
Thank you
Please change your code as below.
MODEL:
public function total_referred_in()
{
$query = $this->db->query('SELECT * FROM daily_out_patient');
return $query->num_rows();
}
Controller
public function referral_in()
{
$data['total_referred_in'] = $this->load->referral->total_referred_in(); //get referral data
$this->load->view("referral_form_view", $data);
}
View :
<span>
<?php
echo $total_referred_in;
?>
</span>
As you can see in Controller line :
$this->load->view("referral_form_view", $data);
$data here is the data array you are passing to your view. In your view you can access data in $data variable by using $data variable's KEY as php variable(In our case its "total_referred_in").
You aren't returning anything from your function, you're just echoing. Try this:
public function total_referred_in()
{
$query = $this->db->query('SELECT * FROM daily_out_patient');
return $query->num_rows();
}
Controller:
public function referral_in()
{
$data['num_rows'] = $this->load->referral->total_referred_in(); //get referral data
$this->load->view("referral_form_view", $data);
}
And then in your view:
<span><?=$num_rows?></span>
I'm working on simple application consisting of simple form. My code really works fine in local environment. But when i uploaded it on a live server gives an error, unable to fetch database fields and i think there is an error in my model.
Here is my model class
class Model_get extends CI_Model
{
function getData($page) {
$query = $this->db->get_where('ci_tbl', array('page' => $page));
print_r($query->result());
return $query->result();
}
}
Here goes my view
<div id="content">
<?php
foreach ($results as $row) {
$title = $row->title;
$para1 = $row->para1;
$para2 = $row->para2;
}
echo heading($title, 1);
?>
<p><?php echo $title;?></p>
<p><?php echo $para1;?></p>
<p><?php echo $para2;?></p>
</div>
My controller goes as
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Site extends CI_Controller {
public function index()
{
$this->home();
}
public function home() {
$this->load->model('model_get');
$data['results'] = $this->model_get->getData('home');
$this->load->view('header');
$this->load->view('nav');
$this->load->view('main_content',$data);
$this->load->view('footer');
}
public function about() {
$this->load->model('model_get');
$data['results'] = $this->model_get->getData('about');
$this->load->view('header');
$this->load->view('nav');
$this->load->view('about_page',$data);
$this->load->view('footer');
}
Make sure you actually return the results of the query:
//print_r($query->result());
return $query->result();
At the moment you've commented out return $query->result(); and you're just printing the result. The controller calling the model isn't going to get that information and therefore isn't passing through to the view.
Also check that the database connection is correct if moving from local to a public environment.
Actually you had an error
foreach ($results as $row) {
$title=$ row->title;
^^^^
It should be
$title = $row->title;
^^^
You need to update your query within model as
class Model_get extends CI_Model {
function getData($page) {
$query = $this - > db - > get_where('ci_tbl', array('page' => $page));
return $query->result_array();
}
}
I have two table in database ::: 1. tbl_category 2. tbl_product.
Showing all category list in home page and when user clicks on signle category then it goes to product page(from tbl_product) by category id (included category id in tbl_product)
Issue ::: I want to show the category Name and Image Here. So that user can see in which category they clicked on (from tbl_category ) ::: how can I get them ??? please help me
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['result']=$this->home_model->selectCategory($config['per_page'], $this->uri->segment(3));
$data['maincontent']=$this->load->view('home_message',$data,TRUE);
$this->load->view('home', $data);
}
public function category($category_id){
$data=array();
$data['result']=$this->home_model->selectProductByCategoryId($category_id);
$data['maincontent']=$this->load->view('category_detail',$data,TRUE);
$this->load->view('home', $data);
}
Model::::
class Home_Model extends CI_Model{
//put your code here
public function selectCategory($per_page, $offset)
{
$this->db->select('*');
$this->db->from('tbl_category');
$this->db->order_by("category_id", "desc");
$query = $this->db->get('', $per_page, $offset);
foreach ($query->result() as $row)
$data[] = $row;
return $data;
}
public function selectProductByCategoryId($category_id)
{
$this->db->select('*');
$this->db->from('tbl_product');
$this->db->where('category_id',$category_id);
//$this->db->order_by("product_id", "desc");
$query_result= $this->db->get();
$result=$query_result->result();
return $result;
}
View::::
I want to show the category Name and Image Here. So that user can see in which category they clicked on ::::
<?php
foreach ($result as $values)
{
?>
<div>
<div>
<img src="<?php echo base_url();?><?php echo $values->product_image ?>" width="90%" height="220" />
</div>
<div>
<b><?php echo $values->product_name ?></b> <br>
<b>Price: <?php echo $values->product_price ?></b> <br>
Order Now
</div>
</div>
<?php } ?>
Controller
public function category($category_id){
$data=array();
$data['result'] = $this->home_model->selectProductByCategoryId($category_id);
// Added this line
$data['category'] = $this->home_model->selectCategoryByd($category_id);
$data['maincontent'] = $this->load->view('category_detail',$data,TRUE);
$this->load->view('home', $data);
}
Model_Home
public function selectCategoryById($category_id)
{
$result = $this->db->select('*')
->from('tbl_category')
->where('id',$category_id)
->get()
->result();
return $result;
}
Then echo some of those in your view.
You are using a Model_Home for other models functions?
Models are for data and everything what has to do with that data. You should have a Model_Category with a selectById function and a Model_Product with a selectByCategoryId AND a selectById function. Models are NOT used to describe pages.
Please read about MVC and CodeIgniters implementation of it. Then refactor your code and properly use codeigniters features which, if implemented correctly, allow you to not even have to write these functions yourself! Note: I do not know CI very well, so I don't know about the specific implementations of e.g. MVC, ORM, and the like
In my controller I went from getting the data right there (which worked fine):
$data['query'] = $this->db->query("MY DB QUERY");
$this->load->view('shopci_view', $data);
to grabbing the data from a class model function:
class Shopci_model extends CI_Controller {
function __construct()
{
parent::__construct(); //model constructor
}
//display sale itmes on shopci_view.php
function sale_items()
{
$query = $this->db->query('MY DB QUERY - SAME AS ABOVE');
return $query->result();
}
}
new controller function:
//load model, auto connect to db
$this->load->model('Shopci_model', '', TRUE);
//Display items for sale
$data['query'] = $this->Shopci_model->sale_items();
$this->load->view('shopci_view', $data);
ERROR:
Fatal error: Call to a member function result() on a non-object in
shopci_view
This is the line in the view that worked before I switched to the model (didn't change view):
<?php foreach($query->result() as $row): ?>
Any help is appreciated.
Thank You.
In your model you return the $query as a result() array to the controller.
So you cannot then use 'foreach $query->result()' again - because you have already done that;
This should work
<?php foreach($query as $row): ?>
OR if you want - just change the model from
return $query->result();
to
return $query;
In your model you want to return the data to pass to the controller. So in your model you would have
function sale_items()
{
$query = $this->db->query(SAME AS OLD);
return $query;
}
and then your controller will be the same and your foreach in your view should be the following
<?php foreach ($query as $row): ?>