Pagination count wrong Cakephp 1.2 - php

I had auction bid list (debit for each auction was equal 1). I changed View code for "Debit" for showing "Auction Id" count. (you can see pic.).
But now I have problem with pagination. It has to show 26 but you can see 93.
I want to show result like in picture but with correct pagination.
Here is my code
In Controller:
$this->paginate = array(
'conditions' => array('Bid.user_id' => $user_id),
'limit' => 100,
'order' => array('Bid.created' => 'desc'),
'contain' => array('Auction' => array('Product'))
);
$this->set('bids', $this->paginate());
In Model: override paginateCount()
function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$sql = "
SELECT user_id,
auction_id,
description,
debit,
COUNT( * ) AS my_auct,
`credit`,
`created`
FROM `bids`
WHERE `user_id` = {$this->User->id}
GROUP BY auction_id, credit
";
$this->recursive = $recursive;
$results = $this->query($sql);
return count($results);
}
How can fix this issue only in controller (not using paginateCount) and put this query result into View (now I made calculating in View).
Thanks in advance!

I solved my problem. Here my code in controller
$this->paginate = array('conditions' => array('Bid.user_id' => $user_id),'fields' => array('COUNT(auction_id) as my_auct', 'Bid.*'), 'group' => array('Bid.auction_id', 'Bid.credit'), 'limit' => 10000, 'order' => array('Bid.created' => 'desc'), 'contain' => array('Auction' => array('Product')));
I found paginateCount function here and added in model:
public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$conditions = compact('conditions');
if ($recursive != $this->recursive) {
$conditions['recursive'] = $recursive;
}
unset( $extra['contain'] );
$count = $this->find('count', array_merge($conditions, $extra));
if (isset($extra['group'])) {
$count = $this->getAffectedRows();
}
return $count;
}
Only thing I can't show in "Credit" column are all values (when I grouped by auction_id and credit, it shows to me only one 15 and 100). I want to show all values in credit column
Any ideas?

Related

How to fix "Call to a member function execute() on string" on my function

I'm modifying a Wordpress API witch is currently getting learnpress course and lessons infos from the database using leanrpress functions only. I need to modify the API to get the scores from the newly implemented plugin h5p, therefor i need to make a new function to access the Database and get the scores from the right table, then put then into an array with the according lesson. The array here is only an exemple i'm using to see if i can get the datas, ut i'm stuck with the error
"Call to a member function execute() on string"
when i try and run it on postman. Could someone lighten me on this issue please ?
function ilp_api_get_progress_by_mail($data){
$mail=$_GET['mail']; //$data->get_param["mail"];
$course_id=$_GET['course'];
global $wpdb;
$user=get_user_by("email",$mail);
if($user !== false){
$lp_user=learn_press_get_user( $user->ID );
if($course_id==NULL){
$all_courses=ilp_api_get_all_courses($data);
}else{
$all_courses=array('courses' => array(array('id' => intval($course_id))));
}
$progress=array();
$i=0;
if($all_courses!=NULL && $all_courses['courses']!=null){
foreach($all_courses['courses'] as $course){
if($lp_user->has_enrolled_course($course['id'])){
$lp_course=learn_press_get_course( $course['id'] );
$course_data = $lp_user->get_course_data($course['id']);
$course_results = $course_data->get_results( false );
$progress[$i]=array(
'id' => $course['id'],
'name' => $lp_course->get_title(), //$course['name'],
'condition' => $lp_course->get_passing_condition(),
'completed' => $course_results['completed_items'],
'total' => $course_results['count_items'],
'progress' => absint( $course_results['completed_items'] / $course_results['count_items'] * 100 ),
'permalink' => $lp_course->get_permalink(),
);
$i++;
}
}
}
$result = array(
'userfound' => true,
'user_id' => $user->ID,
'connect' => get_h5p_grades(),
'courses_progress' => $progress,
'course_id' => $all_courses,
);
function get_h5p_grades(){
global $wpdb;
$ID = 1;
$ID_use = 1;
$result = $wpdb->prepare('SELECT score FROM mci_h5p_results WHERE id = %d AND user_id = %d', $ID, $ID_use);
$result->execute();
$donnees = $result->fetch();
return $donnees;
}

How to increase the performance of this function

How to increase the performance of following function in phalcon framework. There are thousands of records in the table. I tried different ways, but I am stuck the point. How can I increase the efficiency and reduce the execution time. Following are two methods:
public function currentmonthAction()
{
$payload = $this->request->getJsonRawBody();
$this->setDB();
$ticketsmodel = new Tickets();
$fromcitycondition = "";
if( isset($payload->city->id) )
{
$fromcitycondition = "and fromcity='{$payload->city->id}'";
}
try{
$date = new \Datetime($payload->date);
$year = $date->format('Y');
$month = $date->format('m');
$month = '08';
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
/* result for all cities passenger */
$result = array();
// get all cities permutations
$tmpcitiesdata = array();
$rawresultset = Tickets::find (
array(
'columns' => 'fromcity,tocity',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1) ". $fromcitycondition,
'group' => 'fromcity,tocity'
));
foreach ($rawresultset as $rawresult) {
$tmpcitiesdata[$rawresult->fromcity.'-'.$rawresult->tocity]['fromcity'] = $rawresult->fromcity;
$tmpcitiesdata[$rawresult->fromcity.'-'.$rawresult->tocity]['tocity'] = $rawresult->tocity;
}
//var_dump($rawresultset);
// get tickets sold based on cities combinations
$total = 0;
foreach ($tmpcitiesdata as $tmpcities) {
$rawresultset = Tickets::find (
array(
'columns' => 'customer',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1) and fromcity=". $tmpcities['fromcity']." and tocity=".$tmpcities['tocity'],
'group' => 'customer'
));
$totalsoldRaw = count($rawresultset);
// get ticket cancellations
$rawresultset = Tickets::find (
array(
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (3) and fromcity=". $tmpcities['fromcity']." and tocity=".$tmpcities['tocity']
));
//make sure cancellations are tickets cancellations not booking cancellations
foreach($rawresultset as $rawresult)
{
$resultNumber = Tickets::find("departure='$rawresult->departure' and seatno={$rawresult->seatno} and id < {$rawresult->id} and tickettype = 1" );
if( count($resultNumber) > 0 ){
$totalsoldRaw = $totalsoldRaw-1;
}
}
$total += $totalsoldRaw;
array_push($result, array('total' => $totalsoldRaw, 'fromcity' => Cities::findFirstById($tmpcities['fromcity'])->name, 'tocity' => Cities::findFirstById($tmpcities['tocity'])->name));
}
//sort result based on counts
arsort($result);
//cut result to max 6 cities
$result = array_slice($result, 0, 6);
$this->response->setContentType('application/json')
->setJsonContent(
array( 'totaltickets' => $total, "allcities" => $result )
);
$this->response->send();
return;
}
catch(\PDOException $e)
{
$this->response->setStatusCode('422','Invalid Payload');
$this->response->setContentType('application/json')
->setJsonContent(array(
'flash' => array(
'class' => 'danger',
'message' => $e->getMessage()
)
));
$this->response->send();
return;
}
}
Use count instead of count(result of find). Also are you sure in // get ticket cancellations you don't need group ? Then you can select all tickets for customers in 1,3 tickettype and then filter resultset.
Also can't your first $rawresulset can't be:
$rawresultset = Tickets::find (
array(
'columns' => 'customer,fromcity,tocity,tickettype ',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1,3)".$fromcitycondition
'group' => 'customer,fromcity,tocity'
));
?
$ticketCanccelations = $rawresultset->filter(function($row){
if($row->tickettype == 3) {
return $row;
}
});
$resultNumber = Tickets::count("departure='$rawresult->departure' and seatno={$rawresult->seatno} and id < {$rawresult->id} and tickettype = 1" );

How to create multiple conditioner login in codeigniter

my model is here.....but i need to select status of admin ....... but
i m new in codeigniter....and don't no how to select... my need is...
select admin whole detail from table on condition admin status =
active and id=1...
my model is :
public function login($value) {
$query = $this->db->get_where('tbl_admin', $value, 1, 'active');
if ($query->num_rows() > 0) {
$row = $query->row_array();
$sess_arr = array(
'admin_user' => $row['fld_admin_username'],
'adm_key' => $row['fld_admin_key'],
'admin_type' => $row['fld_admin_type'],
'admin_id' => $row['fld_admin_id'],
'admin_logged_in' => TRUE
);
$this->session->set_userdata($sess_arr);
//echo "<pre>";print_r($this->session->all_userdata());exit;
}
else{
$this->session->set_flashdata('error', 'Invalid username/password');
redirect('adminzone');
}
}
The correct syntax for the first line would be:
$query = $this->db->get_where('tbl_admin', array('id' => 1, 'status' => 'active'));
I.e. The second parameter to get_where is an associative array of fields and their values..
Edit: Or perhaps it should be
$query = $this->db->get_where('tbl_admin', array('id' => $value, 'status' => 'active'));
(I am not sure what the $value variable is for here).

Fetch array using both if and while doesn't work

Basically I have 2 methods in the same class, getMovie and getGenres. They are very similar but One doesn't return what I expect.
Here's getMovie method:
public function getMovie($argType, $arg){
$movieQuery = "SELECT id,
rt_id,
imdb_id,
url,
rt_url,
type,
adult,
DATE_FORMAT(release_date, '%Y') AS year,
date_added,
title,
runtime,
budget,
revenue,
homepage,
rating,
tagline,
overview,
popularity,
image,
backdrop,
trailer
FROM movies
WHERE " . $argType . " = " . $arg;
$movieResult = $this->_query($movieQuery);
$movies = array();
if($movieResult->fetch_array(MYSQLI_ASSOC)){
while($m = $movieResult->fetch_array(MYSQLI_ASSOC)){
$movies[] = array( 'title' => $m['title'],
'duplicate' => $m['duplicate'],
'url' => $m['url'],
'rt_url' => $m['rt_url'],
'release_date' => $m['release_date'],
'date_added' => $m['date_added'],
'type' => 'movie',
'adult' => $m['adult'],
'id' => $id,
'rt_id' => $m['rt_id'],
'imdb_id' => $m['imdb_id'],
'rating' => $m['rating'],
'tagline' => $m['tagline'],
'overview' => $m['overview'],
'popularity' => $m['popularity'],
'runtime' => $m['runtime'],
'budget' => $m['budget'],
'revenue' => $m['revenue'],
'homepage' => $m['homepage'],
'image' => $m['image'],
'backdrop' => $m['backdrop'],
'trailer' => $m['trailer'] );
}
return $movies;
}
else{
return false;
}
Here's getGenres method:
public function getGenres($movieId = NULL){
$genresQuery = "";
if($movieId != NULL){
$genresQuery = "SELECT id,
name
FROM genres
WHERE id = ANY (
SELECT genre_id
FROM movie_genres
WHERE movie_id = " . $movieId . ")";
}
else{
$genresQuery = "SELECT id,
name
FROM genres";
}
$genresResult = $this->_query($genresQuery);
$genres = array();
if($genresResult->fetch_array(MYSQLI_ASSOC)){
while($genre = $genresResult->fetch_array(MYSQLI_ASSOC)){
$genres[] = array( 'id' => $genre['id'],
'name' => $genre['name'] );
}
return $genres;
}
else{
return false;
}
}
And here's how I call them:
$mov = $movie->getMovie(2207);
print_r($mov); // output: Array()
$gen = $movie->getGenres(2207);
print_r($gen); // output: Array(values inside)
Both queries do actually return expected values but getMovies method doesn't work with the if statement. It works fine if I just have while loop.
I am using if as well as while as I heard that while loop can sometimes execute even when there's not values. Is there any truth to this? If there is indeed a reason to use an if statement as well as wile loop then why doesn't it work with getMovies method?
Edit 1: I tried storing the array like so but that resulted in a memory related error:
$r = $genresResult->fetch_array(MYSQLI_ASSOC);
if($r){
while($r){
$genres[] = array( 'id' => $genre['id'],
'name' => $genre['name'] );
}
return $genres;
}
I am using if as well as while as I heard that while loop can sometimes execute even when there's not values. Is there any truth to this?
No, according to the php manual mysqli_result::fetch_array returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.
Null is falsy so the while loop will not be entered.
Although the if statement is unnecessary if you had one you would use mysqli_result::$num_rows to check if the query returned any rows.
if($movieResult->num_rows > 0){
while($m = $movieResult->fetch_array(MYSQLI_ASSOC)){
...
}
}

Perform function in a while loop

I have this function that returns a bool(true) or bool(false) if the movement exists.
function movement_performed_today($class_id, $client_id){
$class_id = (int)$class_id;
$client_id = (int)$client_id;
$query = mysql_query("SELECT COUNT(`movement`) FROM `completed_movements` WHERE `class_id` = '$class_id' AND `client_id` = '$client_id' AND `date` = CURDATE()");
$movement_performed = mysql_fetch_row($query);
return ($movement_performed[0] > 0);
}
I have this while loop where I want to call this function and if it returns false perform the function completed_movement. I have tried many different ways but I just can't seem to get it to work. Any info will be much appreciated.
if (empty($_POST)=== false){
$i = 0;
while (isset($_POST["first_name"][$i])) {
$movement_data = array(
'user_id' => $session_user_id,
'class_id' => $class_id,
'class_name' => $class_name,
'client_id' => $_POST['client_id'][$i],
'first_name' => $_POST['first_name'][$i],
'last_name' => $_POST['last_name'][$i],
'nickname' => $_POST['nickname'][$i],
'order' => $_POST['order'][$i],
'movement' => $_POST['movement'][$i],
'rep_set_sec' => $_POST['rep_set_sec'][$i],
'rest' => $_POST['rest'][$i],
'date' => $today
);
//assign variable to the function
$isPerformed = movement_performed_today($class_id, $_POST['client_id'][i]);
//if return false perform this function
if(! $isPerformed){ completed_movement($movement_data);}
$i++;
}
} // if empty
What Im trying to do here is each time it loops through check to see if the function movement_performed_today is true or false. If returns false then insert this _POST data in to db. Not sure if Im doing this correctly because even though the function returns true it still calls the completed_movement function and post the info to db.
I believe the issue may lie here. Earlier this would return true or false but now just returns false even though the movement is present. This code:
$movement_performed = mysql_fetch_row($query);
//return ($movement_performed[0] > 0);
var_dump($movement_performed);
Returns this:
array(1) { [0]=> string(1) "0" }
array(1) { [0]=> string(1) "0" }
If the movement is present shouldn't "0" be "1" or higher depending the number of times it matched up with the query.
Here is the working query:
function movement_performed_today($class_id, $client_id, $movement){
$class_id = (int)$class_id;
$client_id = (int)$client_id;
$query = mysql_query("SELECT COUNT(`movement`) FROM `completed_movements` WHERE `class_id` = '$class_id' AND `client_id` = '$client_id' AND `movement` = '$movement' AND `date` = CURDATE()");
$movement_performed = mysql_fetch_row($query);
return ($movement_performed[0] > 0);
}
Here is the working while loop.
if (empty($_POST)=== false){
$i = 0;
while (isset($_POST["first_name"][$i])) {
$movement_data = array(
'user_id' => $session_user_id,
'class_id' => $class_id,
'class_name' => $class_name,
'client_id' => $_POST['client_id'][$i],
'first_name' => $_POST['first_name'][$i],
'last_name' => $_POST['last_name'][$i],
'nickname' => $_POST['nickname'][$i],
'order' => $_POST['order'][$i],
'movement' => $_POST['movement'][$i],
'rep_set_sec' => $_POST['rep_set_sec'][$i],
'rest' => $_POST['rest'][$i],
'date' => $today
);
//check not already performed today
$isPerformed = movement_performed_today($class_id, $_POST['client_id'][$i], $_POST['movement'][$i]);
//if not performed then do insert
if (! $isPerformed){ completed_movement($movement_data);}
$i++;
}
} // if empty
Thanks guys for all your help!
I may be misreading this but it looks like you are setting $return to true or false, not actually returning the value. I believe you want to change:
$return = $movement_performed[0] > 0;
to
if($movement_performed[0] > 0) return true;
else return false;
Edit:
It sounds like you have trouble with your SQL query as well. Try:
$query = mysql_query("SELECT COUNT(`movement`) FROM `completed_movements` WHERE `class_id` = $class_id AND `client_id` = $client_id AND `date` = CURDATE()");
Since columns class_id and client_id appear to be integers, remove the single quotes around their values.
Edit: Corrected syntax, converted SQL result to integer first.
return ((int)$movement_performed[0] > 0 ? true : false);
If you use this return line, the function completed_movement() will return only booleans.
In this case, you want to be strict when doing comparison logic for calling the function.
You'll want to do this:
//if return false perform this function
if ($isPerformed === false) {
completed_movement($movement_data);
}

Categories