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);
}
Related
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;
}
i am not able to update data through array in Codeigniter (PHP),
I want to update or set column premium_id and premium to 0 when column premium_count reduce to 0
Controller Function :-
$premium_count = !empty($logged_user[0]->premium_count) ? $logged_user[0]->premium_count : '0';
if($premium_count == '0') {
$data = array(
'premium_count' => '0',
'premium_id' => '0',
'premium' => '0'
);
} else {
$data = array(
'premium_count' => $premium_count-1
);
}
$this->admin_model->updateData('users', $data, $this->session->userdata('userid'));
Model Function (sql Query) :-
public function updateData($table,$data,$id)
{
$this->db->where('id',$id);
$this->db->update($table,$data);
}
It works when premium_count has value like 1,2,3.. but when it reduce to 0, It wont update or set above column to 0.
Please try and remove the quotes from 0s.
I mean change
if($premium_count == '0') {
$data = array(
'premium_count' => '0',
'premium_id' => '0',
'premium' => '0'
);
to
if($premium_count == 0) {
$data = array(
'premium_count' => 0,
'premium_id' => 0,
'premium' => 0
);
Hope it helps.
replace this part to place zero as integer instead of string
$premium_count = !empty($logged_user[0]->premium_count) ? $logged_user[0]->premium_count : 0; // <- remove '' over zero
and check like this
if($premium_count == 0) { // <- remove '' over zero
$data = array(
'premium_count' => '0',
'premium_id' => '0',
'premium' => '0'
);
} else {
$data = array(
'premium_count' => $premium_count-1
);
}
I have a foreach loop to loop through a decoded JSON object and run an INSERT on each loop, however I cannot get a SELECT statement to return anything within the same loop.
Here is my Model:
foreach (json_decode($detail, TRUE) as $key => $value)
{
$this->db->select('Type');
$this->db->where(array('AssociationId' => $id, 'BeginDate' => $year, 'Account' => $value['account']));
$query = $this->db->get('GLAccounts');
$account = $query->row_array(); // <- nothing being returned here. Only one row should be returned
if($account['Type'] == 'Asset' || $account['Type'] == 'Expense') // <- so this is being ignored
{
$value['debit'] = 1 * $value['debit'];
$value['credit'] = -1 * $value['credit'];
}
else if($account['Type'] == 'Liablity' || $account['Type'] == 'Capital' || $account['Type'] == 'Income') // <- as is this
{
$value['debit'] = -1 * $value['debit'];
$value['credit'] = 1 * $value['credit'];
}
$values = array(
'id' => NULL,
'JournalId' => $id,
'Date' => $this->input->post('date'),
'Account' => $value['account'],
'Description' => $value['description'],
'Debit' => $value['debit'],
'Credit' => $value['credit']
);
$this->db->insert('GLJournalDetails', $values);
Is my structure wrong? I'f I run that EXACT same code that does the select('Type') using a direct controller->method call from a url and pass in static variables, I get a row_array back. But it's not returning anything inside this loop. The INSERT works just fine.
Try to use
$account = $query->row();
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?
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)){
...
}
}