How to list by highest date in PHP - php

Hey guys so I am having some trouble using the following:
for ($i = 0; $i < count($noncompUsername); $i++)
{
$tsql ="SELECT firstname,lastname,email,phone,statuschangedate FROM csvdata WHERE username = :username ORDER BY statuschangedate";
$tgetmeminfo=$DBH->prepare($tsql);
$tgetmeminfo->execute(array(':username' => $noncompUsername[$i]));
while ($trow = $tgetmeminfo->fetch(PDO::FETCH_ASSOC)){
$csvFirst = $trow['firstname'];
$csvLast = $trow['lastname'];
$csvEmail = $trow['email'];
$csvPhone = $trow['phone'];
$csvDate = $trow['statuschangedate'];
$timediff = strtotime($date) - strtotime($csvDate);
$timediff = floor($timediff/86400);
$sql ="SELECT MailingAdrs FROM insuranceverificationdisclaimer WHERE TraineeUsername = :tusername";
$getmeminfo=$DBH->prepare($sql);
$getmeminfo->execute(array(':tusername' => $noncompUsername[$i]));
while ($row = $getmeminfo->fetch(PDO::FETCH_ASSOC)){
$csvAddrs = $row['MailingAdrs'];
$change = 1;
}
if($change != 1)
{
$csvAddrs = "No address";
}
$change = 0;
echo "$timediff, $csvFirst $csvLast, $csvEmail, $csvPhone, $csvAddrs";
}
echo "
<br>
";
}
Now this works but the part I want to point out is the $tsql ="SELECT firstname,lastname,email,phone,statuschangedate FROM csvdata WHERE username = :username ORDER BY statuschangedate"; - now when I do this and get the integer of the statuschangedate to the current date and print it out as an integer, it is not ordered properly based on the date.
So I need to get this to order by the oldest date on top and as follows...
Thank you!
David

Order the date in descending order (using DESC):
... ORDER BY statuschangedate DESC

If you want to order based on $timediff you should change the ORDER clause to this:
ORDER BY DATEDIFF(:date, statuschangedate)
Granted, this should actually give the same ordering you already had, but you could at least use this expression to save some processing in PHP itself :)

Related

Not able to pass array data

I am trying to create an array in $data, but it is not happening. I am using this code to make a day wise sale chart.
$data = array();
for ($i = 0; $i <= 10; $i++) {
$billdate = date('d-m-Y', strtotime("-$i day"));
$sqlQuery = "select sum(amount),bill_date from msr_bills WHERE bill_date='$billdate' ";
$result = mysqli_query($con, $sqlQuery);
$fetchamount = mysqli_fetch_row($result);
$sum = $fetchamount[0];
$data = new \stdClass();
$data->bill_date = $billdate;
$data->amount = $sum;
$report_JSON = json_encode($data);
echo $report_JSON.",";
}
You can merge your loop into one query, and then iterate over the results instead:
$data = array();
$billdate = date('Y-m-d', strtotime('-10 day'));
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE bill_date >= '$billdate'
GROUP BY bill_date";
$result = mysqli_query($sqlQuery);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = (object)$row;
}
$report_JSON = json_encode($data);
echo $report_JSON;
}
Note that your date format is not compatible with MySQL dates, which are stored in Y-m-d format, and I have changed that in the code. If your bill_date column is actually a text field stored in d-m-Y format, you will need to convert it in the query like so:
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE STR_TO_DATE(bill_date, '%d-%m-%Y') >= '$billdate'
GROUP BY bill_date";
Note also that you can in fact do the computation of $billdate internal to your SQL query using date arithmetic:
$sqlQuery = "SELECT bill_date, SUM(amount) AS amount
FROM msr_bills
WHERE STR_TO_DATE(bill_date, '%d-%m-%Y') >= CURDATE() - INTERVAL 10 DAY
GROUP BY bill_date";
And if you are running MySQL 8.0+, you can do the entire operation in MySQL:
$sqlQuery = "SELECT JSON_ARRAYAGG(data) AS data
FROM (SELECT JSON_OBJECT('bill_date', bill_date, 'amount', SUM(amount)) AS data
FROM msr_bills
WHERE bill_date >= CURDATE() - INTERVAL 10 DAY
GROUP BY bill_date) d";
$result = mysqli_query($sqlQuery);
if ($result) {
$row = mysqli_fetch_assoc($result);
$report_JSON = $row['data'];
echo $report_JSON;
}
Demo on dbfiddle
Put your echo outside loop. remove code $report_JSON = json_encode($data);
$respnseArr = array();
{
.
.
.
$respnseArr[] = $data;
}
echo json_encode($respnseArr);

Predefined counter not updating in select statement

Here's a simplified code similar to what I'm using. In this one, I'm pulling Names from ID's.
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
What I get is the same name, the counter in the select statement stays at 0.
I had to put the definition of the $select statement and the $result inside the loop, it redefines everything every time we enter the while loop, looks like the code below. That doesn't seem practical and optimal to me. What are the best work-around for situations like these? I'm not really familiar with variable scopes in PHP, I haven't found any good documentation on that matter when it comes to sql functions.
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
Here's the code that I've actually written.
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
Your issue doesn't have to do with variable scope. The $select variable is set once as string with the current value of $counter. Your second example works because this value is reset every time.
In your second example however, you're creating a sql statement that gets 1 row (assuming nID is unique), then looping through your result retrieve that one row. You're doing 10 sql calls, but you only need one if you modify your query like so:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
For your actual code, you should be able to get one record per nUserId by using GROUP BY. Try this:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";

PHP/MYSQL Update only first row with defined value

I want to update my database using constraints
for ($count = 0; $count <= $size; $count++) {
if($dayOfTheWeek[$count] == "Friday" or $dayOfTheWeek[$count] == "Saturday"){
$query = "UPDATE rota SET title='Guest' WHERE date = '$dateMonthYearArr[$count]' AND starttime = '22:00'";
$dayresult = mysql_query($query);}
}
I have multiple users with a $starttime of 22:00, but i only want the first users detail to be updated leaving the rest unchanged. how would i go about doing this?
If you only want one record to be changed you can append this to the end of your statement:
LIMIT 1
For example:
$query = "UPDATE rota SET title='Guest' WHERE date = '$dateMonthYearArr[$count]' AND starttime = '22:00' LIMIT 1";

Calculating max logins for each day

I have a database full of php time(); stored when a user logs in.
I know I should have created a value for their username and updated the login count but instead I have a database full of php time(); with their username
Here is how I find the amount of logins for individual users:
<?php
function to_date($timestamp) {
return date('Y-m-d', $timestamp);
}
$days = array();
$occurences = array();
$zero = array();
$query = mysql_query("SELECT `login_time` FROM `stats` WHERE `userid`='$someuserid' ORDER BY `login_time` ASC");
while($rows = mysql_fetch_array($query)) {
$days[] = to_date($rows['login_time']);
}
$days[] = to_date(time());
$occurences = array_count_values($days);
$days = array_unique($days);
sort($days);
for($i = 0; $i < count($days); $i++) {
$difference = isset($days[$i+1]) ? strtotime($days[$i+1]) - strtotime($days[$i]) : 0;
if($difference > 86400) {
$difference = ceil(abs($difference/86400));
$fill = $days[$i];
for($k = 0; $k < $difference-1; $k++) {
$fill += strtotime('+1 day', strtotime($fill));
$zero[] = to_date($fill);
}
}
}
echo "[";
for($i = 0; $i < count($zero); $i++) {
echo "[\"".$zero[$i]."\",0], ";
}
for($i = 0; $i < count($occurences); $i++) {
if($i == count($occurences)-1)
echo "[\"".$days[$i]."\",".($occurences[$days[$i]]-1)."]";
else {
echo "[\"".$days[$i]."\",".$occurences[$days[$i]]."], ";
}
}
echo "]";
?>
How could I apply this to all the users and find out who logged in the most for each day in the database? The output is encoded for jqplot.
SELECT
userid,
DATE(FROM_UNIXTIME(login_time-MOD(login_time,86400)+1)) as logindate,
count(*) as logincount
FROM stats
GROUP BY userid, logindate
Use the above query to get all the required data directly from the database and this will help you avoid doing the post processing using PHP
Additionally, if you would like to get only one record, which have maximum logins in a (any) day, the use the below query with an added SQL wrapper for the above query:
SELECT * FROM (
SELECT
userid,
DATE(FROM_UNIXTIME(login_time-MOD(login_time,86400)+1)) as logindate,
count(*) as logincount
FROM stats
GROUP BY userid, logindate
) tmptable
ORDER BY logincount DESC, logindate DESC LIMIT 1
Let me know if this helped you.
SELECT userid, COUNT(userid) AS 'login_count' FROM stats GROUP BY userid
All the answer may be correct or incorrect. But I know one thing that my answer is not correct.But in the case of Max logins , there is no need of such an answer. Thats all I know.

SQL QUERY returning all results using OR in WHERE statement

Hoping I am just missing something simple here:
$sql = "Select * FROM user_info, user_login WHERE user_login.status = '0' OR user_login.status = '2' AND user_info.uid = user_login.uid";
$db = new connection();
$results = $db->query($sql);
$user = array();
while($info = mysql_fetch_array($results))
{
$user[] = $info;
}
$total = count($user);
//TEST the amount of rows returned.
echo $total;
for ($i = 0; $i < $total; $i++)
{
//echo data;
}
just trying to pull all data that has the user_login.status field set to "0" or "2" but it shows everything thing and it shows the items marked as 2 twice.
Does anyone see my issue?
Your precedence is getting whacked because of missing parentheses:
SELECT DISTINCT *
FROM user_info, user_login
WHERE (user_login.status = '0' OR user_login.status = '2')
AND user_info.uid = user_login.uid
Without seeing the data I can't give you more than a SELECT DISTINCT with regards to the duplicate records.
Select * FROM user_info, user_login WHERE (user_login.status = '0' OR user_login.status = '2') AND user_info.uid = user_login.uid
Order of precedence :)

Categories