SELECT using BETWEEN in MYSQL and PHP Variable - php

I have this code below.
<?php
require_once 'con.php';
$start_time_input = strtotime('08:00:00');
$finish_time_input = strtotime('17:00:00');
$total_time = 0;
$query = mysqli_query($con, "SELECT `start_break`, `finish_break` FROM `break_time` WHERE `start_break` AND `finish_break` BETWEEN '".$start_time_input."' AND '".$finish_time_input."' " );
while($tampil = mysqli_fetch_array($query)){
$start_time_db = strtotime($tampil['start_break']);
$finish_time_db = strtotime($tampil['finish_break']);
if ($start_time_input <= $start_time_db AND $finish_time_input >= $finish_time_db) {
$total_time = (($finish_time_input - $start_time_input) - ($finish_time_db - $start_time_db)) / 3600;
} else {
$total_time = ($finish_time_input - $start_time_input) / 3600;
}
echo $total_time;
}
?>
I try to execute the php file, the page shows me nothing, mysql query seems incorrect. But when I try to run this query in phpmyadmin SELECT start_break, finish_break FROM break_time WHERE start_break AND finish_break BETWEEN '08:00:00' AND '17:00:00' the query gave me the result as expected.
Anyone can help me with this? I've tried to do some research, but as far as I get that I just need to add strtotime to my variable, I did that already and nothing happens.
Any help will be much appreciated.

Here is your current query:
SELECT start_break,
finish_break
FROM break_time
WHERE start_break AND finish_break BETWEEN '08:00:00' AND '17:00:00'
The WHERE clause is saying where start_break evaluates to true, and finish_break is between 8am and 5pm. This probably isn't what you want, because start_break will always evaluate to true. From the MySQL documentation:
MySQL evaluates any nonzero, non-NULL value to TRUE
Besides the logical problem in the WHERE clause, you were also trying to compare the start and finish columns directly against a time-only string. This won't work unless these columns are also time, which I doubt.
Here is the query which you probably logically intended:
SELECT start_break,
finish_break
FROM break_time
WHERE DATE_FORMAT(start_break, '%H:%i:%s') BETWEEN '08:00:00' AND '17:00:00' AND -- both the start break and
DATE_FORMAT(finish_break, '%H:%i:%s') BETWEEN '08:00:00' AND '17:00:00' -- finish break are within range
This assumes that the start_break and end_break columns are datetime and you only want to compare the time of day.

Related

Warning: Trying to access array offset on value of type int in

This code is giving error. I have gone through previous questions. I have used gettype() and it shows that my data is integer. I have tried to convert it to string by using strval() but it didnt work.
I saw this but in dont know how this can be implemented with my code.
sugested similar questions talk about undefined variables.
My problem not undefine but that its value type. variables are defined. It is stored in db as string but when i check its variable type using gettype(), it is an integer. and it seems foreach() doesnt work with integer.
If anyone can help please. i am still in the learning stage.
foreach($schedule_data as $schedule_row)
{
$end_time = strtotime($schedule_row["agent_schedule_end_time"] . ':00');
$start_time = strtotime($schedule_row["agent_schedule_start_time"] . ':00');
$total_agent_available_minute = ($end_time - $start_time) / 60;
$average_inspection_time = $schedule_data["average_inspection_time"];
}
i wrote query
SELECT * FROM agent_schedule_table
WHERE agent_schedule_id = '$agent_schedule_id'
data stored in $schedule_data var_dump ()
array(8) {
["agent_schedule_id"]=> int(18)
["agent_id"]=> string(7) "S1O0NWE"
["agent_schedule_date"]=> string(10) "2022-08-18"
["agent_schedule_day"]=> string(8) "Thursday"
["agent_schedule_start_time"]=> string(5) "08:35"
["agent_schedule_end_time"]=> string(5) "22:35"
["average_inspection_time"]=> int(60)
["agent_schedule_status"]=> string(6) "Active"
}
foreach()
var_dump($end_time); = int(1660595700)
//Agent create appointment for himself
Agent add through a form that has Date: ..., starttime: ...., averagetime: ...., endtime:.....
i wrote query to select from appointemnt the agent appointment time.
i used while() for the stmt-> excute
Problem 1: while loop make it repeat same date and time so many times.
I tried using foreach() or for(), it is not working. I dont know if am using it wrongly or just that it wont work.
Problem 2: what i want to achieve is that the table should;
for every date, role1 start time, role2 start time + average time, role 3 role2time + average time. so the output will be like
peter 22/08 4:00
peter 22/08 4:30,
peter 22/08 5:00 etc
$sql = "SELECT * FROM agent_schedule_table
INNER JOIN agent
ON agent.agent_id = agent_schedule_table.agent_id
INNER JOIN property
ON property.agent_id = agent.agent_id
INNER JOIN rent_interest
ON rent_interest.Property_number = property.Property_number
WHERE (agent_schedule_table.agent_schedule_date >= '$todaysdate' AND property.Property_number = '".$_SESSION["apartment_number"]."')
ORDER BY agent_schedule_table.agent_schedule_date ASC";
$stmt = $pdo->prepare($sql);
$stmt ->execute(array());
$rows = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
$result = $row;
}
I don't think you need a loop. $schedule_data is an associative array, just access the element from there, not from a nested element.
$end_time = strtotime($schedule_data["agent_schedule_end_time"] . ':00');
$start_time = strtotime($schedule_data["agent_schedule_start_time"] . ':00');
$total_agent_available_minute = ($end_time - $start_time) / 60;
$average_inspection_time = $schedule_data["average_inspection_time"];

sugarcrm 6.5 custom where for dashlet not working based on a guide

I am following this guide: here
I followed every step but my problem is that this part of the code is not working as expected:
MyTasksUntilNowDashlet.php
function process($lvsParams = array()) {
global $timedate, $current_user;
$format = $timedate->get_date_time_format($current_user);
$dbformat = date('Y-m-d H:i:s', strtotime(date($format)));
$lvsParams['custom_where'] = 'AND DATE_FORMAT(tasks.date_start, "%Y-%m-%d %H:%i:%s") <= "'.$dbformat.'"';
parent::process($lvsParams);
}
If I do a direct query in my workbench there is a result, but if run trough this function it returns nothing. Is there something wrong with how this was implemented?
Apparently you need to keep a space after the single quote or else your query will be an error.
$lvsParams['custom_where'] = ' AND DATE_FORMAT(tasks.date_start, "%Y-%m-%d %H:%i:%s") <= "'.$dbformat.'"';

PHP - Select data from where timestamp is

I have a piece of code which will select x number of days into the future and print it out.
I'm then trying to select data from those timestamps, and print out accordingly:
Below I am selecting the number of days in the future it should loop ($max) and how many rows/data there is ($data["cnt"])
$stmt=$dbh->prepare("select round((expire - unix_timestamp()) / 86400) as days, count(*) as cnt from xeon_users_rented WHERE user_by=:username group by days;");
$stmt->bindParam(":username",$userdata['username']);
$stmt->execute();
$data=$stmt->fetchAll();
$max = max(array_map(function($d){
return $d['days'];
}, $data));
$expireData = array();
I then loop through x number of days in the future and print it out: (Let's say that $x is = 10)
for($x = 0; $x <= $max; $x++){
if ($data[$x]["cnt"] > 0){
$expireData[] = $data[$x]["cnt"];
}else{
$expireData[] = 0;
}
$stamp = strtotime('+'.$x.' day', time());
$expireDays[] = date("Y/m/d", $stamp);
}
I then print out the days data and the data:
<?php echo implode("', '", $expireDays); ?>
<?php echo implode("', '", $expireData); ?>
Which gives me:
'2014/11/05', '2014/11/06', '2014/11/07', '2014/11/08', '2014/11/09', '2014/11/10', '2014/11/11', '2014/11/12', '2014/11/13', '2014/11/14', '2014/11/15'
and (where each digit represent a value for that specific date)
2,8,0,0,0,0,0,0,0,0
So far so good. The only problem here is, that the data (2,8,0,0etc.) is not correct. It should for example be:
0,0,2,0,0,0,8,0,0,0
My question is: How can I print out the data, where it matches the timestamp (xeon_users_rented.expire)?
To simplify my answer from before and to answer your question directly "How can I print out the data, where it matches the timestamp"?
You need to first put the unix timestamp of "strtotime('+'.$x.' day', time());" into an array from your original loop. Remove the expiredays[] stuff from that loop.
Then loop through that array and then use array_search for finding any matching indexes in the $data array.
if (found in $data array)
$expireDays[] = $data[array_search position]['cnt'];
else
$expireDays[] = 0;
From what I have gathered in what you are trying to establish, the sql query (for example) returns an array such as:
$data = array(
array("days"=>232975857, "cnt"=> 4),
array("days"=>232975867, "cnt"=> 10),
array("days"=>232976689, "cnt"=> 0),
array("days"=>232976688, "cnt"=> 2)
);
The max in your case is 10. However, please note that your code (below):
$max = max(array_map(function($d){
return $d['days'];
}, $data));
could return a lot of PHP E_NOTICE errors and be slow because you are working out a maximum from the unix_timestamp at that stage which is for example 232975867 (far too many loops I suspect that you need). The max should be worked out in the following way I suspect:
$max = count($data);
In my case (from my data example example) this will return something like 4 for which your for loop code will need to reference "<" not "<=". To optimise this I would actually put straight into the for loop "...; $x < count($data); ...;" unless of course you need the $max later.
Here is a big issue for me. I don't see where currently you have any correlation between the $stamp variable and the "days" column from your sql statement. Perhaps I have not seen enough information from you to fully understand or I am interpreting your question incorrectly but your sql for one will not necessarily return the same dates as the stamp variable will calculate and will not certainly return a cnt of 0 for any dates that do not exist in that table. This is why:
if ($data[$x]["cnt"] > 0){
part of the section is unnecessary and possibly incorrect.
To answer your question why do you get "2,8,0,0,0,0...." instead of the order you expected is because the sql does not return 0 cnt values as quite simply the date does not exist in it's table and your implode still returns '0's appended as you forcibly added the 0's afterwords with the line:
$expireData[] = 0;
First of all, you need to fill your data (or re-write your data to contain cnt of '0's in the correct array places). You can achieve this from the sql level with a subquery that ensures missing dates are contained and then a cnt value of 0 is enforced. I'll leave this to you to work out however another way (via PHP) is to do the following (pseudo code):
place each 'stamps' (in unix format) in array from previous loop
forloop $i through $stamps
array_search $stamps against $data['days']
if (found)
$expireDays[] = $data[array_search position]['cnt'];
else
$expireDays[] = 0;
This means that you remove the $expireDays from your first loop.
Finally, perhaps I have misunderstood and that your 'days' column shouldn't match your $stamp dates as those dates are in the future and your 'days' columns are in the past. In this case, your only option is to adjust your sql statement to forcibly include dates that are missing (between a certain date range)
Good luck.

Convert database query from Postgresql to PHP

I am trying to convert an existing select expression in a postgresql query into PHP but appear to be missing part of the calculation.
The relevant field is:
task_start_timestamp > timestamp without time zone
The expression is:
SELECT justify_interval(((EXTRACT(EPOCH FROM age(localtimestamp, task_start_timestamp)) * (1 - task_progress)/COALESCE(NULLIF(task_progress, 0), 1))::int || \' seconds\')::interval) AS task_eta
My conversion in PHP: (Note I added a select localtimestamp as local_timestamp to the query to ensure the calculation is using the same values as the database).
$now = strtotime($item['local_timestamp']);
$task_date = strtotime($item['task_start_timestamp']);
$task_age = $now - $task_date;
$task_eta = $task_age * (1 - $item['task_progress']);
However, the server is returning a different result.
local_timestamp = 2013-02-28 22:53:42.215137
task_start_timestamp = 2013-02-28 22:22:19.255593
task_eta = 00:10:28
php_task_eta = 00:07:50

Subtraction with php and mysql

I am developing a joomla extension and in default.php file i have this code:
foreach($this->subv as $subv) {
$giorni = ((int)$subv->data_fine - (int)$subv->data_inizio);
$ore = ($giorni * 24) % 24;
echo $giorni.' : '.$ore;
}
$this->subv is an object that contains the result of a mysql query. My problem is that echo prints $subv->data_fine value, and not the result of the substraction. $subv->data_fine and $subv->data_inizio contain the result of time() function.
How can i resolve it this problem?
Thanks!
If I understand you problem correctly, $giorni is equal to $subv->data_fine, which would simply mean that (int)$subv->data_inizio evaluates to zero. Have you checked that?
You can use mysql to get the difference between 2 dates (DATEDIFF function):
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff

Categories