Parse PHP Sdk - Can't fetch results by date - php

I have a class named orders and I want to see all the orders that were made this week; for that, I have the following:
$sevenDaysAgo = date('Y-m-d\TH:i:s.u', strtotime('-7 days'));
$query = new ParseQuery("orders");
$query->greaterThanOrEqualTo("createdAt", $sevenDaysAgo);
$count = $query->count();
// The count request succeeded. Show the count
echo "Only " . $count . " Results.";
Knowing that I've already Data that can be shown, with the above code, I am getting 0 results.
Do I have something wrong?

Related

Pagination, wrong amount of results on first page

I'm making news website, and I have mysql db with field "time" like 1533074400
Everything is ok if I just print results from query, but if I want to print only news older than today, I get in result only 2 instead of 5 news on first page. Remaining 3 are on the second page.
The problem is with query, if I receive let's say I have in my database 10 results and only 7 of them are past news, so when I filter them descending by
if ($today > news_date)
I get 2 news on first page (the remaining 3 are invisible future news, blocked by code above) and the rest 5 news on second page. So my question is, what to do to get it properly: 5 news on first page and remaining 2 on second page?
$results_per_page = 5;
if (!isset($_GET['page'])) {
$page = 1;}
else {
$page = $_GET['page'];
}
$this_page_first_result = ($page-1)*$results_per_page;
$sql='SELECT * FROM news ORDER BY time DESC LIMIT ' . $this_page_first_result . ',' . $results_per_page;
$result = mysqli_query($con, $sql);
$number_of_results = mysqli_num_rows($result);
$today = strtotime("now");
while($row = mysqli_fetch_array($result))
{
$news_date = $row[1];
if ($today > $news_date) {
echo HTML;
}
}
$number_of_pages = ceil($number_of_results/$results_per_page);
for ($page=1;$page<=$number_of_pages;$page++) {
echo '' . $page . ' ';
}
Try this:
$sql='SELECT * FROM news WHERE time < '.time().' ORDER BY time DESC LIMIT ' . $this_page_first_result . ',' . $results_per_page;
//Note: time() is an equivalent to strtotime("now")
If you're doing pagination in MySQL you should also do your filtering inside MySQL.
[Edit: Additional explanation] If you paginate in MySQL and then filter in PHP you'll have weird instances like this crop up because MySQL doesn't know where you're intending to actually start from. In this particular example if you have a lot of future-dated items you could actually end up with several blank pages of results pages before you start to see entries.
[Edit edit:] Also, if you do this, you'll no longer need the if check in your PHP loop as MySQL will have already done that.

How can I append a string to an object property?

I am trying to send a response back to my front end with the amount of days in a customers billing period. I query this number but would like to append " Days" after it. So far I have:
<?php
require "../../inc/dbinfo.inc";
$projectnum =$_POST['projectnum'];
$sql = $conn->prepare("SELECT (SELECT TermsofPayment FROM tblCustomers WHERE CUSTOMERID = ProjectCustomer) AS NetTerms FROM tblProjects WHERE PROJECTNOID = ?");
if($sql){
$sql->bind_param("i", $projectnum);
$sql->execute();
$hold = $sql->get_result();
$obj = $hold->fetch_assoc();
$addOn = " Days";
$obj->NetTerms = $obj->{'NetTerms'. $addOn};
echo json_encode($obj);
}
$sql->close();
exit();
?>
After trial and error it appears as though the second last line has no effect on the result. I've looked through the web to find no solutions to this (maybe my search didn't contain the right keywords).
Current Response: {"NetTerms":30}
Desired Response: {"NetTerms":30 Days}
You have/had two problems there:
1st you wanted to concatenate a variable to another one and had a wrong syntax.
$addOn = " Days";
$obj->NetTerms = $obj->{'NetTerms' .$addOn};
// this would try to get a value of `$obj->NetTerms Days`, which doesn't exist.
should have been
$obj->NetTerms = $obj->NetTerms . $addOn;
// or
$obj->NetTerms .= $addOn;
All of this threw an error, because $obj is an array (as return from fetch_assoc()), not an object.
So treat it as an array and it should work:
$obj['NetTerms'] = $obj['NetTerms'] . $addon;

How do I compare a time saved in database with the current time?

I want to compare two times (H:M:S)...
Here's the thing... I want to compare a time saved in a table on my database to the current time that PHP returns to me with date(). However, no comparisons are being made as the session variables (ClassName, ClassStartTime and ClassBlock) return me an undefined index (I believe that is because they are not saving anything so I'm trying to access something that doesn't exist).
How do I compare the times?
NOTE: The time in my database is being saved as data-type TIME, that's why I'm not performing a strtotime() on the variable today_time. Perhaps, that may be my mistake...
<?php
// Obtener hora de registro
date_default_timezone_set('America/Mexico_City');
$today_dW = date('w'); // Get number to know the day of the week. Formatted as {Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6}
$today_time = date('G:i:s'); // Get time. Formatted as {HH : MM : SS}
/*
*/
$class_id_query = "SELECT id_materia, bloque FROM horarios WHERE matricula_prof = '" . $_SESSION['TeacherID'] . "' dia_semana = " . $today_dW . " AND hora_inicio >= " . strtotime($today_time) . "";
// Save query result, if any was found, on var
$class_id_result = $connection->query($class_id_query);
// Check if matching result was found to be posted
if ($class_id_result->num_rows > 0)
{
// Fetch the associated data if any was found
while($row = $class_id_result->fetch_assoc())
{
$_SESSION['ClassID'] = $row['id_materia'];
$_SESSION['ClassStartTime'] = $row['hora_inicio'];
$_SESSION['ClassBlock'] = $row['bloque'];
}
}
Assuming the column hora_inicio is of the type TIME, you do not need strtotime.
$class_id_query = "SELECT id_materia, bloque FROM horarios WHERE matricula_prof = '" . $_SESSION['TeacherID'] . "' dia_semana = " . $today_dW . " AND hora_inicio >= '" . $today_time . "'"
I believe I found an answer...
Thanks to #csb I simulated the query using MySQL function TIME, to extract whatever string that was formatted as a time variable to be returned as time...
Since I'm testing with time, all I'm doing right now is filling up certain tables so more information can be returned. I'll keep you updated with the results, tomorrow.
NOTE: I've found another problem... Certain variables inside the session array DO NOT CHANGE even if the query didn't run or returned another result...
<?php
// Get register time
date_default_timezone_set('America/Mexico_City');
$_SESSION['DayOfWeek'] = date('w');
// Get number to know the day of the week. Formatted as {Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6}
/*
This query must return the class ID, to read its information from the classes table
*/
$class_id_query = "SELECT id_materia, bloque, hora_inicio FROM horarios WHERE matricula_prof = '" . $_SESSION['TeacherID'] . "' AND dia_semana = " . $_SESSION['DayOfWeek'] . "AND TIME(hora_inicio) <= TIME(NOW())";
// Save query result, if any was found, on var
$class_id_result = $connection->query($class_id_query);
// Check if matching result was found to be posted
if ($class_id_result->num_rows > 0)
{
// Fetch the associated data if any was found
while($row = $class_id_result->fetch_assoc())
{
$_SESSION['ClassID'] = $row['id_materia'];
$_SESSION['ClassStartTime'] = $row['hora_inicio'];
$_SESSION['ClassBlock'] = $row['bloque'];
}
}
else
{
$_SESSION['ClassID'] = "";
$_SESSION['ClassStartTime'] = "";
$_SESSION['ClassBlock'] = "";
echo "Query for class ID cannot be performed";
exit();
}
/*
Career logo query.
Logo on ny part of the system
*/
// Query for the class information
$career_logo_query = "SELECT nombre, carrera, cuatrimestre FROM materias WHERE id = '" . $_SESSION['ClassID'] . "'";
// Save query result, if any was found, on var
$career_logo_result = $connection->query($career_logo_query);
// Check if matching result was found to be posted
if ($career_logo_result->num_rows > 0)
{
// Fetch the associated data if any was found
while($row = $career_logo_result->fetch_assoc())
{
$_SESSION['ClassName'] = $row['nombre'];
$_SESSION['CareerName'] = $row['carrera'];
$_SESSION['ClassPeriod'] = $row['cuatrimestre'];
// Show result at index on screen
echo $_SESSION['CareerName'];
}
}
?>_logo.png" alt = "Logotipo de <?php echo $_SESSION['CareerName']; ?>">
Here's an update of the code, I'll update tomorrow showing the results.
Thanks again #csb and #Lilthilion for your help and tips.
I finally got it!
All I needed to do was to transform the time and the query ran, the result i shown below
The result of the query, changing with the time
Now, all that lasts to be done is to get the students list for the form.
Thanks a lot, everybody.
Do you have to compare it with PHP time? What about the database time?
$class_id_query = "SELECT id_materia, bloque FROM horarios WHERE matricula_prof = '" . $_SESSION['TeacherID'] . "' dia_semana = " . $today_dW . " AND hora_inicio >= NOW()"

PHP while loop of mysql queries sometimes returns an empty set randomly (they're not empty, but the result is empty)

I am writing a report on data based on new customers for each given month, starting from the earliest month an order was present all the way to the last month that any orders are present (I realize the current code will stop on any month that doesn't have new customers, and will fix later...)
Some background-- I'm using the Flourish Framework (www.flourishlib.com).. The first month/year is set correctly because I have error log'd it out. The first month with orders is 4/2013.
The problem is that for some reason, MySQL randomly returns an empty result at some point that is completely random. I have run the query for that month/year that it returns an empty result for in a MySQL client and it is not an empty result. The script itself proves this to be the case as where it returns the empty result is random and it will go further than it did before sometimes showing the correct information.
I have tried sleeping in between queries, as I originally thought maybe it was throttling or something, no go. Still the same exact behavior. I have tried using retries (when it encounters a count of 0 it will retry up to X times) and EVERY TIME it's empty, which means it cannot be one of those "sometimes it craps out, try again" type of scenarios.
Here is the code as it is now:
function newClients($month, $year) {
$db = fORMDatabase::retrieve();
$noobs = $db->query("
SELECT
id,
email,
(
SELECT completed
FROM orders
WHERE client_id = clients.id
ORDER BY completed ASC
LIMIT 1
) as first_order
FROM clients
HAVING first_order IS NOT NULL
AND MONTH(first_order) = '$month'
AND YEAR(first_order) = '$year'
AND email NOT LIKE '*#********.com'
AND email NOT LIKE '%#********.com'
AND email NOT LIKE '%#********.com'
AND email NOT LIKE '%#********.com'
AND email NOT LIKE '%#********.com'
AND email NOT LIKE '%#********.org'
AND email != '********#gmail.com'
AND email != '********#********.net'
")->fetchAllRows();
return $noobs;
}
$currentMonth = $theFirst['month'];
$currentYear = $theFirst['year'];
$retries = 0;
$noobs = newClients($currentMonth, $currentYear);
while (count($noobs) > 0 || $retries < 3) {
if (count($noobs) == 0) {
error_log('retry #' . ($retries + 1) . '...');
$retries++;
$noobs = newClients($currentMonth, $currentYear);
error_log('count: ' . count($noobs));
sleep(5);
continue;
}
error_log("loop $currentMonth / $currentYear: " . count($noobs));
if ($currentMonth >= 12) {
$currentYear++;
$currentMonth = 1;
} else {
$currentMonth++;
}
sleep(1);
$noobs = newClients($currentMonth, $currentYear);
error_log('count: ' . count($noobs));
}
Couple additional things.. I censored the email addresses for obvious reasons, and I did look at the actual returned data in the MySQL client, it is correct, and I also did vardump the actual array returned and it is indeed empty. (in case you're wondering that maybe count is counting incorrectly or who knows.. I thought maybe it was a countable object/non-array issue or quirk or something)
There may be some confusion as to the retries etc. as that has nothing to do with my desired outcome and were only attempts to solve the issue, here is the original code:
$noobs = newClients($currentMonth, $currentYear);
while (count($noobs) > 0) {
error_log("loop $currentMonth / $currentYear: " . count($noobs));
if ($currentMonth >= 12) {
$currentYear++;
$currentMonth = 1;
} else {
$currentMonth++;
}
$noobs = newClients($currentMonth, $currentYear);
error_log('count: ' . count($noobs));
}
sorry this is probably not really an answer but too big for comments.
i'm not confident this error is in PHP or flakiness with the db connection
can you modify your retry to print out the query and run it in your mysql client by hand ?
maybe you have weird inputs ?
try adding a null check to this
SELECT completed
FROM orders
WHERE client_id = clients.id
AND completed IS NOT NULL
ORDER BY completed ASC
LIMIT 1
i suspect you have your db set to NULLs first and they float to the top of your ordering

MySQL query doesn't work if user only fills in one field

I'm working in CodeIgniter with a search from that will query the database.
The three fields are "Location" (dropdown list), "Date" (date) and "Event Type" (dropdown list).
The code I'm currently using is:
public function search_flyers($location, $date) {
$date = $this->utils_model->get_sql_date($date);
$query = $this->db->query("SELECT *, flyers.fid FROM flyers
LEFT JOIN event_dates ON flyers.fid = event_dates.fid
WHERE ((flyers.interval='weekly'
AND DATEDIFF('" . $date . "',flyers.start_date)%7=0
AND '" . $date . "' <= flyers.end_date)
OR (flyers.interval='fornightly'
AND DATEDIFF('" . $date . "',flyers.start_date)%14=0
AND '" . $date . "' <= flyers.end_date)
OR (flyers.interval='manual'
AND event_dates.date = '" . $date . "'
OR flyers.start_date = '".$date."'
AND '".$date."' <= flyers.end_date) AND flyers.approved = 1)
AND flyers.location = '".$location."'
GROUP BY flyers.fid
ORDER BY flyers.start_date ASC");
$data['flyers'] = $query->result();
$data['rows'] = $query->num_rows();
return $data;
The Event Date mentioned is being used in conjunction with the "interval" field to work out if an event falls on the date the user has searched for.
The event also has to be approved to be able to show in search results.
The problem is the form does not work if a user only fills in one field.
A previous developer has written this code, and I am charged with the task of making it work.
Normally I would change the AND flyers.location... to OR flyers.location, but that means it would return the results of either the date or the location you specified.
There are several ways to fix this problem, but the quickest is to simply set a default value in the method signature itself.
Instead of
public function search_flyers($location, $date)
you can actually add default values by setting them like this (just an example)
public function search_flyers($location = 'mylocationstring', $date = strtotime("-1 week"))
If the user doesn't choose a date or a location, $date and $location will default to the values you specified.
Now the cleaner way would be to actually verify that the user has filled out the form correctly in the view before letting them submit it. You can do this with CodeIgniter's form validation http://codeigniter.com/user_guide/libraries/form_validation.html by not letting the user run search_flyers($date,$location) if the form validation run is equal to false
if ($this->form_validation->run() == FALSE)
{
//go back to your initial view
}
else
{
$data['results'] = search_flyers($location,$date)
$this->load->view('form success',$data);
}

Categories