Display database table in CodeIgniter - php

I am trying to display a table using CodeIgniter. I made a function to select all data from one table and display it using a foreach loop when the button is clicked. I am getting this error:
Fatal error: Call to undefined method CI_DB_mysql_driver::result() in C:\Xampp\htdocs\Auction\application\models\bidding_model.php on line 47
This is my controller page:
public function viewauction()
{
$this->load->model('bidding_model');
$data['query'] = $this->bidding_model->viewauction();
$this->load->view('auction_view', $data);
}
This is the model:
function viewauction()
{
$query = $this->db->select('products');
return $query->result();
}
This is the view:
<tbody>
<?php foreach($query as $row): ?>
<tr>
<td><?php echo $row->product_id; ?></td>
<td><?php echo $row->auction_id; ?></td>
<td><?php echo $row->start_time; ?></td>
<td><?php echo $row->end_time; ?></td>
</tr>
<?php endforeach; ?>
</tbody>

Just change your model method code to
function viewauction()
{
$query = $this->db->select('*')->from('products')->get();
return $query->result();
}
Hope this helps. Thanks!!

you have to use get()
select() query builder is used for selecting the columns of the table and not the table
example
$query = $this->db->select(array('product_id','auction_id'))
->get('products');
return $query->result();
if you want to select all you can use the get only,
read more at
http://ellislab.com/codeigniter/user-guide/database/active_record.html#select

Your problem is here:
$query = $this->db->select('products');
return $query->result() ;
$query->result() is returning false probably because the products table does not exist. you have to use get instead of select.
Try:
$query = $this->db->get('products');
return $query->result() ;
That could get your started

public function select($table, $field, $value)
{
$this->db->select(*);
$this->db->from('$table');
$this->db->where($field, $value);
$query = $this->db->get();
return $query;
}
I hope the above code will help you.

There is actually a simpler way available.
You should get most from the framework features it is providing,
Use, CodeIgniter's Table Library,
$this->load->library('table'); // Loading the Table Library
$query = $this->db->get('table_name'); // the MySQL table name to generate HTML table
echo $this->table->generate($query); // Render of your HTML table
You can also modify the behavior of HTML generator if you want some custom things like class in table head or body or anything, which you will almost need.
$this->table->set_template($template); // passing an array
Use this line after loading the table library. Use keys from the documentation link below.
Reference: CodeIgniter 3 Table Library - Official Docs

function viewauction()
{
$this->db->select('*');
$this->db->from('tablename');
$query = $this->db->get();
return $query->result();
}
Above code will help you.

Related

Print count value in codeigniter

I want to print count of some records in my project , i tried using some code but no result is giving can anyone figure out the mistake please.
controller
function cart_count()
{
$sess = $this->session->userdata('SESS_USER');
$query = $this->product_model->c_count($sess);
$data['count'] = $query->result();
$query = $this->db->get("cart");
$data['records'] = $query->result();
$this->load->view('frontend/menu',$data);
}
Model
public function c_count($sess)
{
$query =$this->db->query("SELECT COUNT(`product_id`) FROM `cart` WHERE `username`='$sess'");
return $query;
}
View
<?php foreach($count as $count){echo $count;}?>
I see your query using count and where. That is mean you just select 1 row of data like this.
username COUNT(product_id)
admin 3
The return data is just 1 row, so you can return the data using row() like this return $query->row().
Model : return your data default as a row() for 1 row of data.
public function c_count($sess)
{
$query = $this->db->query("SELECT COUNT(product_id) as count_id
FROM cart
WHERE username = '$sess'");
return $query->row();
}
Controller : Call your data here.
function cart_count()
{
$sess = $this->session->userdata('SESS_USER');
$query = $this->product_model->c_count($sess);
$data['count'] = $query->count_id; // CHANGE FROM $data['count'] = $query->result();
// If you dont mind, I change your code :
// $query = $this->db->get("cart");
// $data['records'] = $query->result();
$record = $this->db->get("cart");
$data['records'] = $record->result();
$this->load->view('frontend/menu',$data);
}
Views Here is how to call your data, ill give example using <span>.
<span>Admin total product : <?php echo $count; ?> Products</span>
There is so many ways to call returned data from database.
You can also use <?php echo $query->count_id; ?> in your views without set it into $data['count'] in your controller. You can try it now. :) Hope this help.
Note : If you want to call more than 1 data, dont use where but use a group by. I want to give you an example for that, but it's a different problem with your question. :) and if there any typos, please let me know and I will fix it.
$query =$this->db->query("SELECT COUNT(`product_id`) AS count FROM `cart` WHERE
`username`='$sess'");
change the query to
$query =$this->db->query("SELECT COUNT(`product_id`) as count FROM `cart` WHERE `username`='$sess'");
$query->result() will return array of objects
in view you will get as object you can use
<?php foreach($count as $count){echo $count->count;}?>
or
<?php echo $count[0]->count?>
The issue is with your model class where you fetch the number of row counts.
Actually, in CodeIgniter the result set fetched matches with what the columns of DB tables are.For eg. the statement
$query =$this->db->query("SELECT COUNT(`product_id`) FROM `cart` WHERE `username`='$sess'");
will return a result set something like this
Array ( [0] => stdClass Object ( [COUNT(`product_id`)] => 60 ) )
And when you try to display the result with this line <?php foreach($count as $count){echo $count;}?>
you get error because you are asking to show $count data variable of $count array which is not present.
One simple trick to solve this problem without much changes in your code is to use alias in your query.Just change your query to this
$query =$this->db->query("SELECT COUNT(`product_id`) as 'nums' FROM `products` WHERE `service_id`='$sess'");
And fetch the result in the view as <?php foreach($count as $c){echo $c->nums;}?>
However,in my opinion its better to use inbuilt function num_rows() of CI for this.
Simply use PHP count() function after getting the result
CONTROLLER
function cart_count()
{
$sess = $this->session->userdata('SESS_USER');
$query = $this->product_model->c_count($sess);
$data['count'] = count($query->result());
$query = $this->db->get("cart");
$data['records'] = $query->result();
$this->load->view('frontend/menu',$data);
}

How to output codeigniter selects_sum in the view without foreach

How can I output the result of select_sum from controller to the view without using foreach. I don't want to use foreach because my function returns only 1 number.
The logic is I have a column in DB with numeric values called 'time', I want to sum all of them together, and output the result next to /10000 in my view.
I believe I need to use row() but I am not sure how.
Controller:
$this->load->library(array('form_validation', 'session'));
$this->db->select_sum('time');
$data['num'] = $this->db->get('posts');
$this->db->order_by('id', 'DESC');
$data['query'] = $this->db->get('posts');
$this->load->view('templates/header');
$this->load->view('templates/navigation');
$this->load->view('home_page', $data);
$this->load->view('templates/footer');
View:
<?php foreach ($num->result() as $row): ?>
<?php if (empty($row->time)): echo "0"?>
<?php else: echo $row->time ?>
<?php endif ?>/10000</p>
<?php endforeach;?>
You can combine row() with the variable.
$sql = $this->db->select_sum('time');
$sql = $this->db->get('posts');
$data['num'] = $sql->row();
And you can call in your view
$num->time;
hope this solve your problem.

how call a result from database count(*) on CI

i got code like this on codeigniter :
<?php
$query = $this->db->query("SELECT count(*) FROM data_pribadi WHERE STATUS = 'diterima'");
return $query->result();
?>
how can i call a result?
Try this in your model.
$this->db->select('*');
$this->db->from('data_pribadi');
$this->db->where('STATUS','diterima');
$query = $this->db->get();
return $result=$query->result();
And in your Controller, you can seek the results to your view like the below code
$this->load->model('Mymodel');
$this->load->view('YourviewName',array($data=>$this->Mymodel->Myfunction()));
And these also for your view (example)
<?php
foreach ($data as $u):
echo"<option value ='$u->column_name1'>".$u->column_name. "</option>";
endforeach;
?>
Your code should be placed on model.
Let me guide you.
MODEL:
// file name: Mymodel.php
function test() {
$query = "SELECT count(*) AS total_acc FROM data_pribadi WHERE STATUS = 'diterima'";
return $this->db->query( $query )->row()->total_acc;
}
How about the result?
CONTROLLER
$this->load->model( 'mymodel' ); //available in CI3
$total_acc = $this->mymodel->test();
echo $total_acc;
Done, now you get it. Because your request only produces one row, I think it's suitable for you.
Btw, salam kenal :)

Invalid argument supplied for foreach() due to var_dump is null

Yesterday when I var_dump($this->m_test->result_getGrades());it gave me an array[1356] now it returned null. Can anyone help me figure out why it's NULL? I'm still new in PHP and Codeigniter and its pretty stressful figuring out why I can't retrieve any data from my database.
I assume the reason why I have this error because ($this->m_test->result_getGrades()) is NULL
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/v_display.php
Line Number: 7
Also, What are the factors why I can't retrieve any data from my database? For future references
This is my code:
Controller c_test.php
function getGrades() {
$data['query'] = $this->m_test->result_getGrades();
$this->load->view('v_display', $data);
}
Model m_test.php
function result_getGrades()
{
$this->db->select('grades.blockcode,subjectblocking.subjectcode,subjects.description,grades.final');
$this->db->from('grades');
$this->db->join('subjectblocking','grades.blockcode=subjectblocking.blockcode');
$this->db->join('subjects','subjectblocking.subjectcode=subject.subjectcode');
$this->db->where('2013-F019');
$query=$this->db->get();
}
Views v_display.php
<?php foreach ($query as $row): ?>
<?php echo $row->studentid;?><br>
<?php echo $row->subjectcode;?><br>
<?php echo $row->description;?><br>
<?php echo $row->final;?><br>
<?php endforeach; ?>
Thank you once again! :)
You should try this:
First, you will need to check your where clause.
see example below:
$this->db->where('name', 'test');
that will produce WHERE name = 'test' in the MySQL query
then you have to put a return statement after your get() method:
$query = $this->db->get();
return $query->result_array();
so your model should be something like this:
function result_getGrades()
{
$this->db->select('grades.blockcode,subjectblocking.subjectcode,subjects.description,grades.final');
$this->db->from('grades');
$this->db->join('subjectblocking','grades.blockcode=subjectblocking.blockcode');
$this->db->join('subjects','subjectblocking.subjectcode=subject.subjectcode');
$this->db->where('name of field', '2013-F019');
$query=$this->db->get();
return $query->result_array();
}
There are many faults in your result_getGrades() function :
function result_getGrades()
{
$this->db->select('grades.blockcode,subjectblocking.subjectcode,subjects.description,grades.final');
$this->db->from('grades');
$this->db->join('subjectblocking','grades.blockcode=subjectblocking.blockcode');
$this->db->join('subjects','subjectblocking.subjectcode = subjects.subjectcode');
$this->db->where('your_field', '2013-F019');
$query = $this->db->get()->result();
return $query;
}
There was :
add the return $query;
field name in your where clauses
subject to subjects in your join
var dumping the query itself usually doesn't return much for me usually but it depends on when you dump it.
<?php foreach ($query as $row): ?>
<?php echo $row->studentid;?><br>
<?php echo $row->subjectcode;?><br>
<?php echo $row->description;?><br>
<?php echo $row->final;?><br>
<?php endforeach; ?>
For this you don't need to keep opening and closing the php tags unless you want alot of html around it:
<?php foreach ($query as $row){
echo $row->studentid.'<br>';
echo $row->subjectcode.'<br>';
echo $row->description.'<br>';
echo $row->final.'<br>';
}?>
Notice the . ? It joins the $row->studentid to the html meaning it's alot cleaner code.
Now onto the question, you're assigning a variable as a variable in your foreach...Which is pointless. Thankfully i know the fix. You need to turn the query into a result from your database:
<?php foreach ($query->result() as $row){
echo $row->studentid.'<br>';
echo $row->subjectcode.'<br>';
echo $row->description.'<br>';
echo $row->final.'<br>';
}?>
$query->result() as $row will enable you to echo out the information you get back from the database.
Also at the end of the model, you need to add return $query; otherwise your model is getting the data and not doing anything with it.

Selecting records from a database table in PHP using CodeIgniter and pass to a view

I'm making a query in PHP using CodeIgniter to get the data that I wanted from a database. To be able to get all values for a specific column, I stored it into an array and passed it into a view. But I can do it only for one column.
Here's my code:
$query = $this->db->query('SELECT name, description FROM module');
$result = $query->result_array();
foreach ($result as $key => $rowdata) {
$resultdata['values'][$key] = $rowdata['name'];
}
$this->load->view('myview', $resultdata);
With this scenario I can get all name from the module table. But my problem is, I also wanted to get all the description in the module table, but I don't know how can I implement it and be able to pass it into the view. Hope someone could help me with this. Thanks!
Your not using the MVC pattern!
First you should write your query in a model!
Then load it in your controller like this
$this->load->model('ModelName');
Then call the funcion to retreive the data
$data = $this->modelname->functionToRetreiveData();
Then loop through data with foreach
$dataToView = array();
foreach($data as $key=>$row)
{
$dataToView['something'][$key]['value'] = $row->name_of_column;
}
And pass the array to the view $this->load->view('someview',$dataToView);
Then in the view
foreach($value as $val):
<p><?php echo $val['name']?><p>
endforeach
hi in you way you will do loop twice in controller and then in view to print it check this out
//in controller
$query = $this->db->query('SELECT name,description FROM module');
$resultdata['results'] = $query->result_array();
$this->load->view('myview',$resultdata);
myview.php
foreach($results as $result)
{
echo $result['name'],' ',$result['description'];
}
$query = $this->db->query('SELECT name,description FROM module');
$result = $query->result_array();
foreach($result as $rowdata){
$resultdata['values'][] = $rowdata;
}
$this->load->view('myview',$resultdata);
Try in view:
print_r($values);
You will probably have:
$result[0]['name'], $result[0]['description'] ...
$this->load->database();
$this->db->select('employee');
$query = $this->db->get();
return $query;
foreach ($query as $row) {
print $row->'Name';
.
.
.
print $row->'Address';
}

Categories