PHP if with an array SQL - php

I've got a problem here
$resultContLog = mysql_query("SELECT count(*) FROM dailyLogs WHERE data_log > NOW() - INTERVAL 30 MINUTE and server_id_log=".$Fid.";");
$Adata = mysql_fetch_assoc($resultContLog);
if ($Adata > 0)
{
echo 'OK';
}
else
{
echo 'NOT OK';
}
My php function returns the number of rows; i did this to include new logs if it happen later than 10 minutes. The if ($Adata > 0) statement doesn't work properly. Can you guys help me, please?

to check this , use this
Your need to check for count column you are getting from query if it is grater than zero, here it is used as alias of "total"
$resultContLog=mysql_query("SELECT count(*) as total FROM dailyLogs WHERE data_log > NOW() - INTERVAL 30 MINUTE and server_id_log=".$Fid.";");
$Adata=mysql_fetch_assoc($resultContLog);
if($Adata['total'])
{
echo 'OK';
}
else
{
echo 'NOT OK';
}

You fetch the DB result as an array, thus you can count it:
if (count($Adata)) {
echo 'ok';
} else {
echo 'not ok';
}
Your query is a bit of a mess though. Maybe you could place some logic outside of the SQL.
The date function of PHP is flexible and works good with MySql.
// instead of NOW() - INTERVAL 30 MINUTE
date("Y-m-d H:i:s", time() - 60*30);
Regards
*) edit: What #esqew said

Related

compering times (H:i:s) , ignoring seconds if zero

so i work with a system where i have to do lots of time comparing and by that i mean H:i:s
the problem is sometimes there are 00 for seconds and sometimes it isnt and since times are given to me as string
comparing to similar times with and without second zeros will fail
here we have 2 similar times but my if will fail for missing seconds in one
$db_time = '11:20';
$given_time = '11:20:00' ;
if($db_time == $given_time )
{
echo "same time";
}
else
{
echo "different time";
}
right now i use something like
if( in_array( $given_time , [$db_time , "$db_time:00"] ) )
{
echo "same time";
}
else
{
echo "different time";
}
which is not ideal !! specially since i dont know which one is missing the zeros
i do use with carbon , i prefer if i can solve this by using carbon
$db_time = '11:20';
$given_time = '11:20:00';
if(Carbon::parse($db_time)->eq($given_time)) {
echo "same time";
} else {
echo "different time";
}
You can create Date objects and compare them.
$db_time = '11:20';
$given_time = '11:20:00';
echo isSameTime($db_time, $given_time) ? 'same' : 'different';
function isSameTime(string $time1, string $time2): bool
{
return new DateTime($time1) == new DateTime($time2);
}
echoes
same

User condition online with last login with time()

I searched a bit in the various posts, but I couldn't find a solution for me. However, I would simply like to show the text "Online" and "Offline" to a user based on his last login with time () of less than 5 minutes.
What would be the exact condition?
Thanks a lot to those who will help me.
if($last_login < .....) {
echo "online";
} else {
echo "Offline"
} ?>
Calculate the time 5 minutes ago, and check if the last login was after that:
if ($last_login >= time() - 5 * 60) {
echo "online";
} else {
echo "Offline"
}
The expression (time()-$last_login)/60 will calculate the difference between current time and last login in minutes.
So the code will be:
if(((time()-$last_login)/60) < 5)
{
echo "online";
}
else
{
echo "Offline" ;
}

How to have a sum() with a where clause

I currently have:
// connect for other mins
$sql = "SELECT sum(mins) FROM completed_activity WHERE member_id = '$_SESSION[SESS_MEMBER_ID]' AND exercise != 'Personal Training' AND date >= '$mon'";
But, when the date is not within the where clause, nothing is shown. I'm not even getting my 'else' statement.
Any ideas?
MAYBE SOLVED
I may have got the correct way of doing it with:
$sql = "SELECT sum(CASE WHEN member_id = '$_SESSION[SESS_MEMBER_ID]' AND exercise != 'Personal Training' AND date >= '$mon' THEN mins ELSE 0 END) AS mins FROM completed_activity";
Can anyone confirm if this looks right?
When using SUM, there are at least one result returned. The result of SUM may be 0 or more.
That's why your code is not working correctly.
Try the following code:
// connect for other mins
$sql = "SELECT sum(mins) AS mins_sum FROM completed_activity WHERE member_id = '$_SESSION[SESS_MEMBER_ID]' AND exercise != 'Personal Training' AND date >= '$mon'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$mins = $row["mins_sum"];
if ($mins > 0) {
echo "yes";
} else {
echo "no";
}
}
I dont know php code, But When No condition matched sql query will return 0.
Means There will be atleast 1 record. So your if condition will always true.
Improve condition to check for value like
if ($result['sum'] > 0) { //Check for syntax
while($row = $result->fetch_assoc()) {
$mins = $row["mins"];
echo "yes";
}
} else {
$mins = 0;
echo "no";
}

Is there anyway way to logically compare PHP DateTime objects?

This is part of a simple project that logs payroll hours as a datetime object in MySQL 5.5. I am trying to compare two datetime values to see if they are at least 30 minutes apart. Sounds simple enough but the value of $lastshiftend keeps being set to the same value as $mealendtime and I don't see where or how. That seems to be the only problem but there definitely could be other things I am missing. TIA.
if ($result = mysqli_query($conn, $select)) {
$row_count = mysqli_num_rows($result);
if($row_count == 1) {
// 30 Minute Meal Break
$lastshiftend = new DateTime($row[3]);
$mealendtime = new DateTime('NOW');
$mealtime = $mealendtime->diff($lastshiftend);
$mealminend = $lastshiftend->add(new DateInterval(PT30M));
// $mealminend = $lastshiftend->modify('+ 30 minute');
if($mealendtime < $mealminend) {
echo '<br>Colorado State law requires meal breaks to be at least 30 minutes in length.';
echo '<hr>Main Menu';
} else {
echo 'Log it!';
// header("Location: ./ActionClockIn.php");
}
} else {
echo 'Error! If you ended up here something broke!.';
echo '<hr>Main Menu';
}
}
Unless you use DateTimeImmutable() your DateTime objects will be modified when you call methods like DateTime::add() or DateTime::modify()
$lastshiftend = new DateTimeImmutable($row[3]);
// Now $lastshiftend is unchanged
$mealminend = $lastshiftend->add(new DateInterval(PT30M));
It looks like you will need that for both DateTime objects
$lastshiftend = new DateTimeImmutable($row[3]);
$mealendtime = new DateTimeImmutable(); //"NOW" is not necessary
$mealtime = $mealendtime->diff($lastshiftend);
$mealminend = $lastshiftend->add(new DateInterval(PT30M));

taking the latest content from a dynamic array

A small background of myself is that I'm fairly new to php. I work as an IT assistant and have been asked to edit one of the pages our designers use for samples. I cannot point you to the page as it is an internally hosted page.
I'm honestly not even sure if the question is asked correctly but please bear with me.
The page has a 'request completion date' field within a table that outputs 6 dates in a list, the designers only want it to output the latest date from that list instead of all 6, usually these will be empty so it's no use having them printed.
The code to put them is as follows;
if ($database_data['request_confirmed_comp_date'] > "0")
{ $request_confirmed_completion_date = date("d/m/Y", $database_data['request_confirmed_comp_date']); }
else
{ $request_confirmed_completion_date = " -"; }
if $database_data['request_confirmed_comp_date2'] > "0")
{
$request_confirmed_completion_date2 = date("d/m/Y", $database_data['request_confirmed_comp_date2']);
}
else
{
$request_confirmed_completion_date2 = " -";
}
if ($database_data['request_confirmed_comp_date3'] > "0")
{
$request_confirmed_completion_date3 = date("d/m/Y", $database_data['request_confirmed_comp_date3']);
}
else
{
$request_confirmed_completion_date3 = " -";
}
if ($database_data['request_confirmed_comp_date4'] > "0")
{
$request_confirmed_completion_date4 = date("d/m/Y", $database_data['request_confirmed_comp_date4']);
}
else
{
$request_confirmed_completion_date4 = " -";
}
if ($database_data['request_confirmed_comp_date5'] > "0")
{
$request_confirmed_completion_date5 = date("d/m/Y", $database_data['request_confirmed_comp_date5']);
}
else
{
$request_confirmed_completion_date5 = " -";
}
if ($database_data['request_confirmed_comp_date6'] > "0")
{
$request_confirmed_completion_date6 = date("d/m/Y", $database_data['request_confirmed_comp_date6']);
}
else
{
$request_confirmed_completion_date6 = " -";
}
if ($database_data['request_date_required'] > "0")
{
$request_date_required = date("d/m/Y", $database_data['request_date_required']);
}
else
{
$request_date_required = "-";
}
if ($database_data['request_date'] > "0")
{
$request_date = date("d/m/Y", $database_data['request_date']);
}
else
{
$request_date = "-";
}
It is then called into play using;
echo '<td><b>1.</b>'.$request_confirmed_completion_date.'<br /><b>2.</b>'.$request_confirmed_completion_date2.'<br /><b>3.</b>'.$request_confirmed_completion_date3.'<br /><b>4.</b>'.$request_confirmed_completion_date4.'<br /><b>5.</b>'.$request_confirmed_completion_date5.'<br /><b>6.</b>'.$request_confirmed_completion_date6.'</td>';
Now I may not have much php knowledge, but I know that's a horribly long way of doing that. Is there anyway that I could pull the latest date out of an array, created by the the first block of code, and then output them into the table.
Thanks for any help or advice, even if you could just point me in the right direction as to what loop to use would be helpful.
Edit: I've uploaded the full file online here, hopefully that will clear up some confusion.
You want to use the php function asort. Since all of your values look to be numeric, you should be able to do a standard sort and pull off the last item with array_pop.
It might look something like this:
asort($database_data);
$latest = array_pop($database_data);
echo date('m/d/Y', $latest);
Create an array with the variable names, like if the variables are $A, $B and $C, then
$vars = array("A","B","C");
foreach($vars as $var_name){
if($database_data[$var_name] > "0")
$$var_name = $database_data[$var_name];
else
$$var_name = "-";
}
Note: A, B and C are dummy variable names, as the variable names are too long in your code :-)
Firstly there is a problem with your if conditions, you can't say $x > "0" because with using double-quotes you are using 0 as a string. You should use integer $x > 0.
Now here my answer :
I couldn't understand your system very well, so i'm assuming always there will be 6 dates.
for($q = 0;$q < 6; $q++)
{
if($database_data[...][$q] > 0)
$dates[] = date("d/m/Y", $database_data['...'][$q]);
else
$dates[] = " - ";
}
As you see, you have to fetch your database datas as an array $database_data['...'][].
If you can tweak the original SQL statement, which probably looks something like this:
select request_confirmed_comp_date, request_confirmed_comp_date2, request_confirmed_comp_date3, request_confirmed_comp_date4, request_confirmed_comp_date5, request_confirmed_comp_date6
from sometablename
where somefield='something'
You can tweak it to use shorter (and consistent) field names
select request_confirmed_comp_date as date1, request_confirmed_comp_date2 as date2, request_confirmed_comp_date3 as date3, request_confirmed_comp_date4 as date4, request_confirmed_comp_date5 as date5, request_confirmed_comp_date6 as date6
from sometablename
where somefield='something'
And then in PHP use an array to iterate over the field names like so:
<?php
$lastCompletionDate=""; //start by assuming there was no completion date
for($i=1;$i<=6;$i++) { //check to see if any field is after the last known completion date
if ($database_data['date'.$i] && (date("d/m/Y", $database_data['date'.$i]) > $lastCompletionDate)) {
//if so, store the new date
$lastCompletionDate=date("d/m/Y", $database_data['date'.$i]);
}
}
if($lastCompletionDate) {
echo "The last completion date was $lastCompletionDate\n";
}else {
echo "There was no completion date.\n";
}
?>
An alternative solution would be to use the SQL engine's own internal functions to find the highest date like so:
select greatest(request_confirmed_comp_date,
request_confirmed_comp_date2,
request_confirmed_comp_date3,
request_confirmed_comp_date4,
request_confirmed_comp_date5,
request_confirmed_comp_date6) as greatestcompdate
from sometablename etc...
and then refer to that in PHP like
<?php
if($database_data['greatestcompdate']) {
echo "There was a greatest completion date and it was $database_data[greatestcompdate]";
}
?>

Categories