Prasad Prasad -4 years ago 79
PHP Question

I need to fetch data from database and display in my view using php codeigniter

I am fetching the data from the database.But I am getting error.Here I need to display product name and image in the page.But I am getting the error undefined variable 'name' in the page. Please check my code give your valuable suggestions,Thank you.

My controller

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class productdisplay_ctrl extends CI_Controller {

public function __construct() {
parent::__construct();

$this->load->helper('url');
$this->load->model("productdisplay_model");
}

public function productfetch(){

$this->load->model("productdisplay_model");
$result = $this->productdisplay_model->fetchData();
$data['name'] = $result->sub3_category_name;

$this->load->view('home', $data);
}

}

?>


my model

<?php

class productdisplay_model extends CI_Model {

function __construct() {
parent::__construct();
}

public function fetchData() {

$this->db->where($where);
$this->db->order_by('rand()');
$this->db->select('*');
$this->db->from('sub3_category');
$query = $this->db->get();

if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}

return $data;
}
return false;
}

}

?>


my view

<div class="container-main">

<div class="col-xs-12 col-sm-4 col-md-3">
<div class="prod-container">
<a href="<?php echo base_url(); ?>index.php/welcome/productlist">
<div class="prod_img">
<img src="<?php echo base_url();?>images/img-electronics.jpg" width="100%"/>
</div>
<div class="prod_desc">
<div class="prod-round-icon"></div>
<h4 class="prod_title"><?php echo $name; ?></h4>
<p class="prod_text">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>


<div class="view-more"> view more</div>
</a>
</div>
</div>

Answer Source

Change in model.like this.use row() which returns result in object format having matched row.so that you can access columns using arrow operator.

And what about your $where variable.set it.

public function fetchData() {

            $this->db->select('*');
            $this->db->where($where);
            $this->db->order_by('rand()');
            $this->db->from('sub3_category');
            $query = $this->db->get();

            if ($query->num_rows() > 0) {

                return  $query->row();
            }
            return false;
        }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download