Unable to retrieve status count after passing Mysql query - php

Currently I'm using CodeIgniter to retrieve my data in a particular timeframe. All these entries have a status. I am trying to get a count of all the data that are present in the particular time frame. Currently this is my model class where I have the following entry to return all the entries in a particular date range:
public function get_records($st_date,$end_date){
$this->db->select('*');
$this->db->from('crm_listings');
$this->db->where('cast(added_date as date) BETWEEN "' . $st_date . '" AND "' . $end_date . '" AND status= "D"');
return $this->db->count_all_results();
}
And my controller class:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
class Testcontroller extends CI_Controller
{
public function index()
{
$this->load->view('crm/test');
}
function fetch_status(){
$output ='';
$startDate = '';
$endDate = '';
$this->load->model('crm/user_model');
if($this->input->post('startDate')){
$startDate = $this->input->post('startDate');
}
if($this->input->post('endDate')){
$endDate = $this->input->post('endDate');
}
$data = $this->user_model->get_records($startDate,$endDate);
$output .= '
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tr>
<th>Draft</th>
</tr>
';
if($data->num_rows() > 0)
{
$output .= '
<tr>
<td>'.$data.'</td>
</tr>
';
}
else
{
$output .= '<tr>
<td colspan="7">No Data Found</td>
</tr>';
}
$output .= '</table>';
echo $output;
}
}
?>
So as of now when I comment everything in my controller class after $data and just make a statement echo $data; I get the output I want. But when I'm wrapping it around <td>'.$data.'</td>, it doesn't give an output.

Edit your function at line echo $this->db->count_all_results();
function get_records($st_date,$end_date){
echo $this->db->count_all_results();// change this code
// to
return $this->db->get();
}
for make sure there is any data, try to print_r($data) after you call that method/function
$data = $this->user_model->get_records($startDate,$endDate);
print_r($data) // check data

Related

Undefined property PHP error on Codeigniter

I am super stuck on a problem. I went through many solution give here related to this but I did not found any solution to my error.
this is the error message I am facing and I used print_r to view what is the output but is also a dead end.
My controller - Search.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Search extends CI_Controller {
function index(){
$this->load->model("ModSearch");
$data["get_ztable"] = $this->ModSearch->get_zscore();
$data["get_course"] = $this->ModSearch->getCourse();
$data["get_stream"] = $this->ModSearch->getStream();
$data["get_district"] = $this->ModSearch->getDistrict();
$data["get_uni"] = $this->ModSearch->getUniversity();
$this->load->view('addZscore',$data);
}
Model - ModSearch.php
public function get_zscore(){
$query = $this->db->get('tbl_zscore');
return $query;
}
View - addZscore.php
<table style="width:50%">
<tr>
<th>Z ID</th>
<th>Z Score</th>
</tr>
<?php echo print_r($get_ztable);?>
<?php
if($get_ztable->num_rows() > 0)
{
foreach ($get_ztable as $row)
{
?>
<tr>
<td><?php echo $row->z_id; ?></td>
<td><?php echo $row->z_score; ?></td>
</tr>
<?php
}
}else{
echo 'Database Error(' . $this->db->_error_number() . ') - ' . $this->db->_error_message();
}
?>
</table>
You have to make changes in your model function that must return a "result" that you can easily use in your view. So just replace
return $query
with
return $query->result()
Or make a change in your foreach loop in views from
foreach($get_ztable as $row)
to
foreach($get_ztable->result() as $row)

join query with bonfire (codeigniter)

I'm trying to do a join query in bonfire (which is great for the beginner i am btw)
I first tried to set a public function in the method, but after a while, i though it would be better to put it in the controller (maybe i'm wrong...?)
However, i guess my join request is valid, but i can't get it in my view...
Here is my controller:
class Patient extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('post_model');
Template::set_block('search/search', 'search/search');
//Template::set('toolbar_title', 'Manage Your Blog');
Template::set_theme('custom', 'default');
Template::set_block('nav', 'nav');
}
public function detail($id = null) {
$this->load->helper('typography');
$this->load->model('operation_model');
$this->db->select('*');
//$this->db->from ('operation AS ope');
$this->db->from('operation');
$this->db->join('patient', "patient.zkp_pat = operation.zkf_pat ");
$query = $this->db->get();
$post = $this->post_model->find($id);
//Template::set('post', $query);
Template::set('post', $post);
Template::set_view('detail');
Template::render();
}
}
And my view file:
<code>
<div class="post">
<?php
echo ($post->nom . ' ');
echo ($post->prenom . ' ');
echo ($post->zkp_pat . ' ');
echo ($post->dob);
foreach ($query as $row) :
echo ($row->zkf_pat . ' ' );
echo "titre de l'opération: " . ($row->titre);
endforeach;
?>
</div>
</code>
Thanks for your advices and help !
I asked for help on the BF forum too, and somebody gave me the solution=>hopefully this will help somebody else. The issue was with the $query , which is a DB_result object.
http://www.codeigniter.com/user_guide/database/query_builder.html#selecting-data
to solve the problem i had to doo: $query->result()
Final code:
Controller:
public function detail ($id = null){
$this->load->helper('typography');
$this->db->from ('operation as ope');
$this->db->join ('patient',
"patient.zkp_pat = ope.zkf_pat " );
$this->db->where ('patient.zkp_pat', $id);
$query = $this->db->get();
$post = $this->post_model->find($id);
Template::set('query', $query);
Template::set('post', $post);
Template::set_view('detail');
Template::render()
}
And view file:
<div class="post">
<h2><?php e($post->nom); ?></h2>
<?php
echo ($post->nom . ' '); echo ($post->prenom . ' ');
echo($post->zkp_pat . ' ');
echo ($post->dob);
foreach ($query->result() as $row) :
echo '<div>'
echo " \n";
echo ($row->zkf_pat . ' ');
echo "titre de l'opération: " . ($row->titre);
?>
</div>
<?php
endforeach;
?>
</div>
$query->get()->result() returns an object with all fetched data,
whereas $query->get()->row()returns only a single result row, if the result has one row, it returns only the first one. The result is given as an object...
If you like my edit, please upvote, that would be very helpful !

How to convert php script to codeigniter MVC?

I have PHP script and work:
<?php
$con=mysqli_connect("localhost","root","","dbm");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result3 = mysqli_query($con,"select t.tgl_transaksi, p.kode_produk, tp.hp_tujuan, d.nama as nama2, sr.ket as ket2 from dbm.transaksi_psa tp
left join dbm.transaksi t
on tp.id_transaksi=t.id_transaksi
left join dbm.produk p
on tp.kode_produk = p.kode_produk
left join dbm.set_report sr on t.status=sr.jenis
left join dbm.distributor d on (tp.id_distributor=d.id_distributor and tp.com=d.com)
where date(t.tgl_transaksi)=date(now())
order by t.tgl_transaksi DESC");
echo "
<div class='table-responsive'>
<table class='table table-hover' id='t01'>
<tr>
<th>Tanggal</th>
<th>Produk</th>
<th>Tujuan</th>
<th>Suplier</th>
<th>Status</th>
</tr>";
while ($row = mysqli_fetch_array($result3))
{
echo "<tr>";
echo "<td>" . $row['tgl_transaksi'] . "</td>";
echo "<td>" . $row['kode_produk'] . "</td>";
echo "<td>" . $row['hp_tujuan'] . "</td>";
echo "<td>" . $row['nama2'] . "</td>";
echo "<td>" . $row['ket2'] . "</td>";
echo "</tr>";
}
echo "</table></div> <br><br><br>";
mysqli_close($con);
?>
And I try change to Codeigniter MVC - OOP:
Models:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ikhtisar_model extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//read the ikhtisar list from db
public function get_all()
{
$this->db->select('t.tgl_transaksi AS tgl, p.kode_produk AS kode, tp.hp_tujuan AS nohp, d.nama AS nama2, sr.ket AS ket2', FALSE)
->from('transaksi_pulsa tp')
//$this->db->where('date(t.tgl_transaksi)', 'date(now())');
->join('transaksi t','tp.id_transaksi=t.id_transaksi', 'left')
->join('produk p','tp.kode_produk = p.kode_produk', 'left')
->join('set_report sr','t.status=sr.jenis', 'left')
->join('distributor d','tp.id_distributor=d.id_distributor and tp.com=d.com', 'left')
->order_by("t.tgl_transaksi", "DESC");
$ikhtisar = $this->db->get();
//->result_array();
//return $ikhtisar;
}
}
Controllers:
<?php
if ( ! defined('BASEPATH')) exit('Akses di blok. Cek kembali link yang Anda tuju!');
class ikhtisar extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
}
public function index()
{
//load the ikhtisar_model
$this->load->model('ikhtisar_model');
//call the model function to get the ikhtisar data
$ikhresult = $this->ikhtisar_model->get_all();
$data['ikhlist'] = $ikhresult;
//load the ikhtisar_view
$this->load->view('templates/header', $data);
$this->load->view('ikhtisar_view',$data);
$this->load->view('templates/footer', $data);
}
}
Views:
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<div class="page-content">
<div class="row">
<div class="col-md-12 col-sm-12">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Tanggal</th>
<th>Produk</th>
<th>Tujuan</th>
<th>Suplier</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<? foreach($ikhtisar->result_array() as $ikh): ?>
<tr>
<td><?=$ikhlist['tgl']?></td>
<td><?=$ikhlist['kode']?></td>
<td><?=$ikhlist['nohp']?></td>
<td><?=$ikhlist['nama2']?></td>
<td><?=$ikhlist['ket2']?></td>
</tr>
<? endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
But, what I get, the data doesn't display at all. The header, the footer, display correctly.
First you have to return data from your model
class Ikhtisar_model extends CI_Model{
public function get_all()
{
.........................
$ikhtisar = $this->db->get();
return $ikhtisar;
}
}
second you have to pass data to your view from contorller. You already did it.
public function index()
{
//load the ikhtisar_model
$this->load->model('ikhtisar_model');
//call the model function to get the ikhtisar data
$ikhresult = $this->ikhtisar_model->get_all();
$data['ikhlist'] = $ikhresult;//you got it and you will get your variable as $ikhlist at your view
//load the ikhtisar_view
$this->load->view('templates/header', $data);
$this->load->view('ikhtisar_view',$data);
$this->load->view('templates/footer', $data);
}
Now display at your view.You wrote foreach loop worng.It should be like this
<? foreach($ikhlist->result_array() as $ikh): ?>
<tr>
<td><?=$ikh['tgl']?></td>
<td><?=$ikh['kode']?></td>
<td><?=$ikh['nohp']?></td>
<td><?=$ikh['nama2']?></td>
<td><?=$ikh['ket2']?></td>
</tr>
<? endforeach; ?>
better use full php tag instead of short tag.like this
<?php instead of <?
and
<?php echo instead <?=
Thanks for helping me, Mr. Shaiful Islam. All I get, this error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: ikhtisar
Filename: ikhtisar/ikhtisar_view.php
Line Number: 19
Tanggal Kode No HP Nama2 Ket2
( ! ) Fatal error: Call to a member function result_array() on a non-object in /var/www/html/cinew/application/views/ikhtisar/ikhtisar_view.php on line 19
Call Stack
# Time Memory Function Location
1 0.0001 131424 {main}( ) ../index.php:0
2 0.0003 132712 require_once( '/var/www/html/cinew/system/core/CodeIgniter.php' ) ../index.php:202
3 0.0063 340720 call_user_func_array ( ) ../CodeIgniter.php:359
4 0.0063 340852 ikhtisar->index( ) ../CodeIgniter.php:359
5 0.3295 372728 CI_Loader->view( ) ../ikhtisar.php:20
6 0.3295 373004 CI_Loader->_ci_load( ) ../Loader.php:419
7 0.3296 390908 include( '/var/www/html/cinew/application/views/ikhtisar/ikhtisar_view.php' ) ../Loader.php:833
Line 19 on the file:
<?php foreach($ikhtisar->result_array() as $ikh): ?>
PS: I'm sorry for using "Post Your Answer". This is not my solution answer for my own problem really. I can't use code in the comment.

(EDITED QUES) PHP - Call function within another function

I have referred to similar questions like this and have done exactly the same way as it should have been but no success. Hence I would appreciate if some one can help me with this
I have a file called view.php which calls a function from a class based on a switch case condition. This function displays the output on the page with few links. When clicked on the link it calls another function which sits in my first function. But obviously when I click my link, nothing happens. That's my code.
view.php
require_once(..'/functions.php');
$functions = new myfile_functions();
<form method="post" action="view.php"><div>
<p><select name="potentialareas" id="potentialareas">
<option style="font-weight:bold;" value="-1">Select an area to view </option>
<?php
foreach($accessareas as $accessarea){
echo "<option value='".$accessarea->id."'>".$accessarea->name. " - " . $accessarea->reporttype. "</option>";
}
?>
</select>
</p>
<p><input name="view" id="view" type="submit" value="View" title="view" /><br /></p>
</div></form>
<div style="border-top:1px dotted #ccc;"></div>
<?php
if(isset($_POST['view']))
{
$hierarchyid = $_POST['potentialareas'];
$reporttype = $DB->get_record_sql("some query");
switch($reporttype->reporttype)
{
case "D Report":
$functions->getDepartmentReport($hierarchyid);
break;
case "S Report":
$functions->getSectionReport($hierarchyid);
break;
case "A Report":
$functions->getAreaReport($hierarchyid);
break;
}
}
functions.php
class myfile_functions(){
function getDepartmentReport($departmentid)
{
global $USER, $CFG, $DB;
$dname = $DB->get_record_sql("some query");
$output = "<div id='actualreport'><p><b>" . $dname->name. " Department Report</b></p>";
$output .= "<p>Activities started: </p>";
$output .= "<p>Activities Completed: </p></div>";
$output .= "<div id='separator' style='border-top:1px dotted #ccc;'></div>";
$output .= "<div id='listofsections'><p><b><i>Select the following for a more detailed report.</i></b></p>";
$snames = $DB->get_records_sql('some query');
foreach($snames as $sname)
{$output .= "<p>" .$sname->name. " <a href='view.php?section=" .$sname->id. "' name='section'><i>view report</i></a></p>";
}
$output .= "</div>";
if(isset($_GET['section']))
{
$this->getSectionReport($_GET['section']);
}
echo $output;
}
function getSectionReport($sectionid)
{
global $USER, $CFG, $DB;
$sname = $DB->get_record_sql("some query");
$output = "<div id='actualreport'><p><b>" . $sname->name. " Report</b></p>";
$output .= "<p>Num Users: </p>";
$output .= "<p>Activities Completed: </p></div>";
$output .= "<div id='separator' style='border-top:1px dotted #ccc;'></div>";
$output .= "<div id='listofareas'><p><b><i>Select the following for a more detailed report.</i></b></p>";
$anames = $DB->get_records_sql('some query');
foreach($anames as $aname)
{$output .= "<p>" .$aname->name. " <a href='view.php?area=" .$aname->id. "' name='view' id='view'><i>view report</i></a></p>";
}
$output .= "</div>";
if(isset($_GET['area']))
{
$areaid = $_GET['area'];
$this->getAreaReport($areaid);
}
echo $output;
}
Similarly another function calling the above function, n so on.
function getAreaReport($id)
{ .. same content but calling another function...}
So when ever I click my view report link, I get the id appended id in my querystring, something like
http://mydomain.com/view.php?section=5
Ideally the contents of getSectionReport() should get printed but its not. Please point out what is it that I am doing wrong.
Thanks in advance.
What's your main method for displaying everything? At the moment you have three functions, all of which link to eachother in various ways, but it doesn't look as if you're instantiating anything first. The PHP is being fed a parameter in your URL, sure, but if a class isn't instantiated and a method declared, how does it know what you want it to do?
For myfile.php, maybe you should do something like:
class MyFile
{
public function other_function()
{
// Various stuff
return 'stuff';
}
public function other_other_function()
{
// Various other stuff
return 'other stuff';
}
public function page_view($file_id)
{
$var = $this->other_function($file_id);
return $this->other_other_function($var);
}
}
$class = new MyFile;
echo $class->page_view($_GET['id']);
If the two functions are part of a class (as your comment above hints), then the call should be written as
$this->getUserReport($id);
If you're accessing a sibling function inside the same class, use:
class ClassName
{
public function sibling_function()
{
return 'Hey bro!';
}
public function my_function()
{
return $this->sibling_function();
}
}
If not, use the standard:
public function my_function()
{
return sibling_function();
}
If you're still having trouble, make sure your class is properly instantiated. There's no point calling another function if you're not even instantiating the class first:
$obj = new ClassName;
echo $obj->my_function();

PHP/SQL - Display Rows Created After a Certain Date

I created classes Rankings and DateFilter.
Each rankings class has a DateFilter class that should produce the cutoff date. I am trying to be able to create a filter so that everything created after that date will be displayed in a table.
However, the comparison does not work. Can you see a problem?
Here is my DateFilter class:
<?php
include ("Filter.php");
class DateFilter extends Filter
{
//#param daysOld: how many days can be passed to be included in filter
//Ex. If daysOld = 7, everything that is less than a week old is included
private $interval;
public function DateFilter($daysOld)
{
$this->interval = new DateInterval('P'.$daysOld.'D');
}
//#Return: Returns a DateTime that is the earliest possible date to be included in the filter
function createLimitDate()
{
$now = new DateTime();
return $now->sub($this->interval);
}
//generates SQL code for checking date
//Ex. WHERE limitDate > created... if > means before
function genSQL()
{
$limitDate = $this->createLimitDate();
return $limitDate->format('Y-m-d') . " < 'created'";
}
}
?>
And my Rankings Class:
<?php
class Rankings
{
private $filter;
//#params: $filty is the filter given to these rankings
public function Rankings($filty)
{
$this->filter = $filty;
}
//#return: returns the html code for the rankings
public function display()
{
echo '<table border="1" align="center">'.
'<tr align="center" style="font-weight:bold;">
<b><td>#</td><td>NAME</td><td>Date</td></b>
</tr>
';
//hardcoding DB
$where = $this->filter->genSQL();
$qry = mysql_query("SELECT * FROM `pix`
WHERE $where
");
if (!$qry)
die("FAIL: " . mysql_error());
$i = 1;
while($row = mysql_fetch_array($qry))
{
$name = $row['uniquename'];
$created = $row['created'];
echo ' <tr>
<td>'. $i . '</td>'.
'<td>' . $name . '</td>'.
'<td>'. $created . '</td>'.
'</tr>';
$i += 1;
}
echo '</table>';
echo $where;
}
}
?>
I'm calling it like this:
$test = new DateFilter(100);
$rankings = new Rankings($test);
$rankings->display();
In that example, nothing is displayed, even though I'm sure everything in my datebase was uploaded less than 100 days ago.
Throw in some quotes around the date you're passing to MySQL, and drop the quotes around your column name:
return "'" . $limitDate->format('Y-m-d') . "' < created";

Categories