How to load database data to table using codeigniter - codeigniter

I want to display my database record in a table, but I don't get it. I don't know whats wrong in my code but it displays empty result. I have attached my model and view. I am using codeigniter framework. Any help would be much appreciated..
Here is my model:
public function display_data(){
$query = $this->db->query("SELECT * FROM sales_rep_tbl;");
if($query->num_rows > 0){
$this->table->set_heading(
"SR_Code",
"SR_Fname"
);
foreach($query->result() as $r){
$bg = "black";
$this->table->add_row(
"<div class = '".$bg."'>".$r->SR_Code."</div>",
"<div class = '".$bg."'>".$r->SR_Lname."</div>",
"<div class = '".$bg."'>".$r->SR_Fname."</div>"
);
$data.= $this->table->generate().br();
}
return $data;
}
}
And my view:
<div class = "container" >
<div class = "row" style = " height:400px; width:auto; margintop:20px;" >
<div class = "col-xs-12">
<?php echo $this->Main_Page_Model->display_data();?>
</div>
</div>
</div>

Please Follow the MVC structure of CI.
You Controller Should be:
public function veiw_table() {
$data= $this->yourModel->yourfunction();
$this->load->view('yourViewPage', ['data' => $data]);
}
Your Model Should Be:
public function yourfunction() {
$query = $this->db-
->select('*')
->get('yourTableName');
return $query ->result();
}
IN View:
foreach ($data as $singleData){
echo $singleData->columnNam;
}
Hope This will Help You

Related

Trying to get a variable pagination to show me 3 different types of paginations

Here is my Index:
<div class="page-sizer">
<a class="page numbers" href="{{$references->pagination(10)}}">10</a>
<a class="page numbers" href="{{$references->pagination(30)}}">30</a>
<a class="page numbers" href="{{$references->pagination(100)}}">100</a>
<button href="qweqwe.qweqwe" class="btn btn-info float-right>112e1e1e1e"></button>
</div>
My AdminreferenceController:
public function index()
{
$references = Reference::orderBy('priority', 'desc')->orderBy('id', 'desc')->paginate(50);
return view('admin.reference.index', ['references' => $references]);
}
and my Lengthawarepaginator:
public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])
{
foreach ($options as $key => $value) {
$this->{$key} = $value;
}
$this->total = $total;
$this->perPage = $perPage;
$this->lastPage = max((int) ceil($total / $perPage), 1);
$this->path = $this->path !== '/' ? rtrim($this->path, '/') : $this->path;
$this->currentPage = $this->setCurrentPage($currentPage, $this->pageName);
$this->items = $items instanceof Collection ? $items : Collection::make($items);
}
. i currently get the error Method Illuminate\Database\Eloquent\Collection::pagination does not exist.
I want to have 3 buttons that show 3 different kinds of paginations like in stackoverflow in the search bar at the bottom.
You are calling pagination in collection try like this
first you need to include the DB class before class deceleration
use Illuminate\Support\Facades\DB;
Then change the query like this
$references = DB::table('reference')->orderBy('priority', 'desc')->orderBy('id', 'desc')->paginate(5o);
return view('admin.reference.index', ['references' => $references]);
In you view you need to access like this
{{ $references->links() }}
https://laravel.com/docs/5.7/pagination
i have currently changed the pagination completly. i wrote a url with
/x/y/perpage/10,
/x/y/perpage/30,
/x/y/perpage/100,
i made a new route for it
route::('/x/perpage/{count})'
and changed my AdminReferenceController to
public function index($perpage = false)
{
if(!$perpage) {
$perpage = 10;
}
$references = Reference::orderBy('priority', 'desc')->orderBy('id', 'desc')->paginate($perpage);
I couldn't get time to work this out. But I found you calling pagination() instead of paginate. See my suggetion
<div class="page-sizer">
<a class="page numbers" href="{{$references->paginate(10)}}">10</a>
<a class="page numbers" href="{{$references->paginate(30)}}">30</a>
<a class="page numbers" href="{{$references->paginate(100)}}">100</a>
<button href="qweqwe.qweqwe" class="btn btn-info float-right>112e1e1e1e"></button>
</div>
Here I removed the paginate from index() and returns collection.
public function index()
{
$references = Reference::orderBy('priority', 'desc')->orderBy('id', 'desc');
return view('admin.reference.index', ['references' => $references]);
}
Hope this helps you.

how to view individual field of the table in codeigniter

I have created following table in mysql
I want to retrieve one of the field i.e abstract or author or Title by using id dynamically in view field.
These are my model, controller and view code.
Model:This is my model
$this->db->select("*");
$this->db->limit(10);
$this->db->from("abcde");
$query = $this->db->query("SELECT * FROM abcde ORDER BY DocumentID ASC");
Controller: this is my controller here
$this->load->model("Sample_model");
$data["fetch_data"] = $this->Sample_model->fetch_data();
$data['view']='services_view';
$this->load->view('load_view', $data);
return $query;
View:This is my view page
<?php
if($fetch_data->num_rows() > 0)
{
foreach($fetch_data->result() as $row)
{
?>
<tr>
<td><?php echo $row->Abstract
</tr>
<?php
}
}
?>
</table>
The above view is displaying all the record of abstract.I want to use ID in view so that i can get specific abstract in one line.
for example display abstract where id=1 or display author where id 3.Important point is here that i want to use id in view of the codeigniter. I will be grateful to you for your help.
Hope this will help you :
You can use custom helper to get the desired result
Add a file in your helpers folder name custom_helper.php and autoload with autoload.php like this :
$autoload['helper'] = array('custom');
In your custom_helper.php add a function like this :
function get_abstract($id)
{
$ci = & get_instance();
$query = $ci->db->get_where('abcde',['id' => $id]);
return $query->row()->abstract;
}
in your view call this get_abstract function like this:
<?php
if($fetch_data->num_rows() > 0)
{
foreach($fetch_data->result() as $row)
{
?>
<tr>
<!-- get abstract by id like this -->
<td><?php echo get_abstract($row->id);?></td>
</tr>
<?php }
}?>
Update : your controller should be like this :
public function services()
{
$this->load->model("Sample_model");
$data["fetch_data"] = $this->Sample_model->fetch_data();
$data['view']='services_view';
$this->load->view('load_view', $data);
}
Your model fetch_data should be like this :
function fetch_data()
{
$this->db->order_by("DocumentID" ,"ASC");
$this->db->limit(1);
$query = $this->db->get('prlaps');
return $query;
}
Update for View with using row() instead of result():
<?php
if($fetch_data->num_rows() > 0)
{
$row = $fetch_data->row();
echo get_abstract($row->id);
}?>

Load images from database CodeIgniter

I would like to create a photo gallery, taking images from the database.
I'm using codeigniter.
Database
this is a static page located in views/pages/gallery.php
does anyone have any ideas?
What you want is to query the database table, get the relevant fields, and return that to a view. In MVC, it looks something like this:
Model:
class Portfolio_model extends CI_Model {
public function get_items() {
$this->db->select('name, description, image');
$this->db->order_by('date', 'DESC');
$q = $this->db->get('tablename'); // your tablename here
if ($q->num_rows() > 0) {
return $q->result();
} else {
return null;
}
}
}
Controller:
class Portfolio extends CI_Controller {
public function index() {
$this->load->helper('html');
$this->load->model('portfolio_model');
$data['items'] = $this->portfolio_model->get_items();
$this->load->view('portfolio', $data);
}
}
View:
if (!is_null($items)) {
foreach ($items as $item) {
echo $item->name . '<br>';
echo $item->description . '<br>';
echo 'Image src: ' . base_url() . $item->image . '<br>'; // might need slash after base_url, don't remember
echo img($item->image);
}
} else {
echo 'No items found!';
}
This worked for me :
Controller -
public function index(){
$this->load->model('galleryModel');
$data1['items'] = $this->galleryModel->get_items();
$this->load->view('gallery', $data1);
}
Model -
public function get_items() {
$this->db->select('*');
$this->db->from('gallery');
$query = $this->db->get();
if($query->num_rows() != 0){
return $query->result_array();
}else{
return false;
}
}
View -
<?php
foreach ($items as $item) {
$image_id = $item['image_id'];
$name = $item['name'];
$category = $item['category'];
$image = $item['image'];
?>
<div class="tile scale-anm <?php echo $category; ?>">
<img src="<?php echo $image; ?>" class="film-img-gallery" alt="" />
</div>
<?php } ?>

passing multiple queries to view with codeigniter

I am trying to build a forum with Codeigniter.
So far i have the forums themselves displayed and the threads displayed, based on the creating dynamic news tutorial.
But that is 2 different pages, i need to obviously display them into one page, like this:
Forum 1
- thread 1
- thread 2
- thread 3
Forum 2
- thread 1
- thread 2
etc.
And then the next step is obviously to display all the posts in a thread. Most likely with some pagination going on. But that is for later.
For now i have the forum controller (slimmed version):
<?php
class Forum extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('forum_model');
$this->lang->load('forum');
$this->lang->load('dutch');
}
public function index()
{
$data['forums'] = $this->forum_model->get_forums();
$data['title'] = $this->lang->line('title');
$data['view'] = $this->lang->line('view');
$this->load->view('templates/header', $data);
$this->load->view('forum/index', $data);
$this->load->view('templates/footer');
}
public function view($slug)
{
$data['forum_item'] = $this->forum_model->get_forums($slug);
if (empty($data['forum_item']))
{
show_404();
}
$data['title'] = $data['forum_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('forum/view', $data);
$this->load->view('templates/footer');
}
}
?>
And the forum_model (also slimmed down)
<?php
class Forum_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_forums($slug = FALSE)
{
if ($slug === FALSE)
{
$query= $this->db->get('forum');
return $query->result_array();
}
$query = $this->db->get_where('forum', array('slug' => $slug));
return $query->row_array();
}
public function get_threads($forumid, $limit, $offset)
{
$query = $this->db->get_where('thread', array('forumid', $forumid), $limit, $offset);
return $query->result_array();
}
}
?>
And the view file
<?php foreach ($forums as $forum_item): ?>
<h2><?=$forum_item['title']?></h2>
<div id="main">
<?=$forum_item['description']?>
</div>
<p><?=$view?></p>
<?php endforeach ?>
Now that last one, i would like to have something like this:
<?php foreach ($forums as $forum_item): ?>
<h2><?=$forum_item['title']?></h2>
<div id="main">
<?=$forum_item['description']?>
</div>
<?php foreach ($threads as $thread_item): ?>
<h2><?php echo $thread_item['title'] ?></h2>
<p><?=$view?></p>
<?php endforeach ?>
<?php endforeach ?>
But the question is, how do i get the model to return like a double query to the view, so that it contains both the forums and the threads within each forum.
I tried to make a foreach loop in the get_forum function, but when i do this:
public function get_forums($slug = FALSE)
{
if ($slug === FALSE)
{
$query= $this->db->get('forum');
foreach ($query->row_array() as $forum_item)
{
$thread_query=$this->get_threads($forum_item->forumid, 50, 0);
}
return $query->result_array();
}
$query = $this->db->get_where('forum', array('slug' => $slug));
return $query->row_array();
}
i get the error
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: models/forum_model.php
Line Number: 16
I hope anyone has some good tips, thanks!
Lenny
*EDIT***
Thanks for the feedback.
I have been puzzling and this seems to work now :)
$query= $this->db->get('forum');
foreach ($query->result() as $forum_item)
{
$forum[$forum_item->forumid]['title']=$forum_item->title;
$thread_query=$this->db->get_where('thread', array('forumid' => $forum_item->forumid), 20, 0);
foreach ($thread_query->result() as $thread_item)
{
$forum[$forum_item->forumid]['thread'][]=$thread_item->title;
}
}
return $forum;
}
What is now next, is how to display this multidimensional array in the view, with foreach statements....
Any suggestions ?
Thanks
You are using row_array() hence your error, change your get_forums() to:
$thread_query=$this->get_threads($forum_item['forumid'], 50, 0);
But I believe you should actually be using result_array() since you want a list of all forums.

codeigniter view, add, update and delete

I'm newbie in codeigniter and still learning. Anyone can help for sample in basic view, add, update, delete operation and queries in codeigniter will gladly appreciated.
Just a simple one like creating addressbook for newbie.
thanks,
best regards
Some sample queries in Codeigniter
class Names extends Model {
function addRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->insert("names");
return $this->db->_error_number(); // return the error occurred in last query
}
function updateRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->update("names");
}
function deleteRecord($yourname) {
$this->db->where("name", $yourname);
$this->db->delete("names");
}
function selectRecord($yourname) {
$this->db->select("name, name_id");
$this->db->from("names");
$this->db->where("name", $yourname);
$query = $this->db->get();
return $this->db->result();
}
function selectAll() {
$this->db->select("name");
$this->db->from("names");
return $this->db->get();
}
}
More information and more ways for CRUD in codeigniter active record documentation
More about error number over here
A sample controller
class names_controller extends Controller {
function addPerson() {
$this->load->Model("Names");
$name = $this->input->post("name"); // get the data from a form submit
$name = $this->xss->clean();
$error = $this->Names->addRecord($name);
if(!$error) {
$results = $this->Names->selectAll();
$data['names'] = $results->result();
$this->load->view("show_names", $data);
} else {
$this->load->view("error");
}
}
}
More about controllers over here
A sample view - show_names.php
<table>
<tr>
<td>Name</td>
</tr>
<?php foreach($names as $row): ?>
<tr><td><?ph echo $row->name; ?></td></tr>
<?php endforeach; ?>
</table>
More about codeigniter views over here
You can use this as an example
class Crud extends Model {
// selecting records by specifying the column field
function select()
{
// use $this->db->select('*') if you want to select all the records
$this->db->select('title, content, date');
// use $this->db->where('id', 1) if you want to specify what row to be fetched
$q = $this->db->get('mytable');
// to get the result
$data = array();
// for me its better to check if there are records that are fetched
if($q->num_rows() > 0) {
// by doing this it means you are returning array of records
foreach($q->result_array() as $row) {
$data[] = $row;
}
// if your expecting only one record will be fetched from the table
// use $row = $q->row();
// then return $row;
}
return $data;
}
// to add record
function add()
{
$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
);
$this->db->insert('mytable', $data);
}
// to update record
function update()
{
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', 1);
$this->db->update('mytable', $data);
}
// to delete a record
function delete()
{
$this->db->where('id', 1);
$this->db->delete('mytable');
}
}
Some of this are from codeigniter userguide.
To view the records,
If return data is array of records,
foreach($data as $row)
{
echo $row['title'] . "<br />";
}
If the return data is an object (by using $q->row),
echo $data->title;
This is just a few examples or CRUD in Codeigniter. Visit the codeigniter userguide.

Resources