issues with DATETIME in database - php

I have devised the following code; to calculate the waiting time and expected time for a patient. The code should also echo a warning if the patient has been waiting too long.
Please note: Waiting_time is DATETIME in the database.
Here is the code;
<?php
$conn = mysqli_connect("localhost","root","") or die ("No connection");
mysqli_select_db($conn, "a&e") or die('Could not select database.');
$query = "SELECT PatientID, Forename, Surname, Gender, Illness, Priority, Arrival_time,NOW() as now,ABS(TIMEDIFF(NOW(), Arrival_time)) as Waiting_Time FROM Patient";
$result = mysqli_query($conn, $query) or die("Invalid query");
echo "<table border='1'>
<tr>
<th>PatientID</th>
<th>Forename</th>
<th>Surname</th>
<th>Gender</th>
<th>Illness</th>
<th>Priority</th>
<th>Waiting Time</th>
</tr>";
while ($row = $result->fetch_object()){
//Select the expected and discharge time for this patient.
$query2 = "SELECT Abs(TIMEDIFF(Expected_Time,'00:00:00')) as Expected,Abs(TIMEDIFF(Discharge_Time,'00:00:00')) as Discharge ".
"FROM priority_time ".
"WHERE Illness = '".$row->Illness."'".
" AND Priority = '".$row->Priority."'".
";";
$result2 = mysqli_query($conn, $query2) or die("Invalid statement: ".$query2);
$row2 = $result2->fetch_object();
$expected = $row2->Expected;
$discharge = $row2->Discharge;
echo "expected-> ".$expected." discharge-> ".$discharge;
if($expected > $discharge){
echo "There is a problem with the database consistency, expectedTime must be less than dischargeTime!";
}
//Set the patient color.
if($row->Waiting_Time < $expected && $row->Waiting_Time < $discharge){
echo "<tr>";
}
if($row->Waiting_Time >= $expected && $row->Waiting_Time < $discharge){
echo '<tr bgcolor="#FFFF00">';
}
if($row->Waiting_Time > $expected && $row->Waiting_Time > $discharge){
echo '<tr bgcolor="#FF0000">';
}
//Print patient info
echo
"<td>" . $row->PatientID . "</td>
<td>" . $row->Forename . "</td>
<td>" . $row->Surname . "</td>
<td>" . $row->Gender . "</td>
<td>" . $row->Illness . "</td>
<td>" . $row->Priority . "</td>
<td>" . $row->Waiting_Time . "(".$expected."-".$discharge.") </td>";
//Close row
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
EDIT:
On each row, in the column Waiting Time it is showing the waiting time in seconds, and in brackets the currentTime a minus and the arrival time, just for checking. How do I convert the waiting time to the format hh:mm:ss to have a better representation for the user?
Showing;
Waiting time
01:15:42(10500.000000-10500.000000)
Why is it displaying (10500.000000-10500.000000)?

Try this:
gmdate("H:i:s", $seconds)
If that doesn't work, have a look at How to convert seconds to time format?
Update:
To do this in the SQL statement try something like this:
SELECT TIME_TO_SEC(TIMEDIFF('2013-03-27 12:00:00', '2013-03-27 10:00:00')) diff;
So something like this:
SELECT PatientID
, Forename
, Surname
, Gender
, Illness
, Priority
, Arrival_time
, NOW() as now
, TIME_TO_SEC(TIMEDIFF(NOW(), Arrival_time)) as Waiting_Time
FROM Patient;
Then you would change this line:
<td>" . $row->Waiting_Time . "(".$expected."-".$discharge.") </td>
to this:
<td>" . gmdate("H:i:s", $row->Waiting_Time) . "(".$expected."-".$discharge.") </td>

When dealing with dates and times in php strtotime() is your biggest friend. Lucky the date() function is all you need for this. Something that is going to convert seconds to a readable format could be the following.
$time = strtotime('now');
echo $time . '<br />';
$var = date('H:i:s',$time);
echo $var;

Related

Mysql Query Getting Item as ID in 2 different tables

Im sorry for my bad english but this is the best i can.
I am trying to make a script that get's the item values of one line in my
for this example i'll be using the row with ID 2.
The first query is working correctly and getting the 2 values of 1items and 2items and deletes the ; that comes with it.
But the second part seems a little bit harder and i can't solve it.
The query is getting id, base_item from the table
The last 2 Outputs marked red are the one's that are matching 1items & 2items
I'm trying to let the if statement filter the $item1 as id in the item table and output the baseitem of the found row
same goes for item2
I'm using MySQL & MySQLi because this cms doesnt support newer versions of PHP yet.
<?php
$query = "SELECT * FROM logs_client_trade ORDER by id DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$item1 = rtrim($row['1items'],"; ");
$item2 = rtrim($row['2items'],"; ");
echo("<tr>");
echo("<td>" . $row['id'] . "</td>");
echo("<td>" . $row['1id'] . "</td>");
echo("<td>" . $row['2id'] . "</td>");
$userinfo = "SELECT id, base_item FROM items LIMIT 1";
$result2 = mysql_query($userinfo) or die(mysql_error());
while($row2 = mysql_fetch_assoc($result2)){
echo("<td>");
if($row2['id'] == $item1){ echo $row2['baseitem']; } else echo "Not available";
echo ("</td>");
echo("<td>");
if($row2['id'] == $item1){ echo $row2['baseitem']; } else echo "Not available";
echo ("</td>");
}
$tradetime = $row['timestamp'];
$date = date("d M Y - H:i:s", $tradetime);
echo("<td>$date</td></tr>");
}
?>
You forgot the while loop for the second query:
$userinfo = mysql_query("SELECT id, base_item FROM items");
while($get2 = $userinfo->fetch_assoc()) {
$baseid = $get2['id'];
$baseitem = $get2['baseitem'];
echo("<tr>");
[...]
}
In addition to that, your code is a mess. In the second loop you are still listing the rows from the logs table... I suggest you to review carefully your code, being careful on how you are using the different $row and $get2 arrays.
You can use a JOIN to get all of the info with one SQL statement:
SELECT *
FROM `logs_client_trade` a
LEFT JOIN `items` b
ON REPLACE(a.`1items`,';','') = b.`id`
LEFT JOIN `items` c
ON REPLACE(a.`2items`,';','') = c.`id`
ORDER by a.`id` DESC
UPDATE:
Here's the PHP code that will run the query and output the table rows. I've specified the column names based on the code in the original question.
<?php
$query = "SELECT
a.`id`,
a.`1id`,
a.`2id`,
a.`1items`,
a.`1items`,
IFNULL(b.`baseitem`,'Not Available') as `baseitem1`,
IFNULL(c.`baseitem`,'Not Available') as `baseitem2`,
DATE_FORMAT(a.`timestamp`,'%d %m %Y - %H:%i:%s') as `tradetime`
FROM `logs_client_trade` a
LEFT JOIN `items` b
ON REPLACE(a.`1items`,';','') = b.`id`
LEFT JOIN `items` c
ON REPLACE(a.`2items`,';','') = c.`id`
ORDER by a.`id` DESC
";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$item1 = rtrim($row['1items'],"; ");
$item2 = rtrim($row['2items'],"; ");
echo "<tr>\r\n";
echo " <td>" . $row['id'] . "</td>\r\n";
echo " <td>" . $row['1id'] . "</td>\r\n";
echo " <td>" . $row['2id'] . "</td>\r\n";
echo " <td>" . $row['baseitem1'] . "</td>\r\n";
echo " <td>" . $row['baseitem2'] . "</td>\r\n";
echo " <td>" . $row['tradetime'] . "</td>\r\n";
echo("</tr>\r\n");
}
?>

Display sum of timestamps as 00:01:26 instead of 126

I'm working on a site where workers' hours are calculated based on when they clock in (start) and clock out (end). end - start = total. I have successfully computed the difference between the start and end. The start, end, and total are inserted into a DB. The "Shift total" comes from the SQL SUM of total in the db. The last foreach statement is the code in question. I want to format the "Shift total" as 00:00:00 so that it would show as 00:01:26 instead of 126. I have tried ". $row['SUM(total)'] + '00:00:00' . " but it didn't work. Any suggestions on how I should go about this? Thanks in advance. I pasted the results first then the code.
____start____________end____________total
10:44:46 AM 10:44:49 AM 00:00:03
10:50:12 AM 10:50:14 AM 00:00:02
10:50:27 AM 10:50:32 AM 00:00:05
11:12:02 AM 11:13:18 AM 00:01:16
Shift total --> 126
$sql3 = "SELECT date, startTime, endTime, total FROM timeSheet WHERE userName='$user_name'";
$sql4 = "SELECT SUM(total) FROM timeSheet WHERE userName='$user_name'";
echo "<table border='1'>
<tr>
<th>date</th>
<th>start</th>
<th>end</th>
<th>total</th>
</tr>";
foreach ($conn->query($sql3) as $row) {
$start = explode (" ", $row['startTime']);
$end = explode(" ", $row['endTime']);
if ($start[1] == '00:00:00'){
$start[1] = '0';
}else if ($end[1] == '00:00:00'){
$end[1] = '0';
}else{
$start[1] = date("h:i:s A", strtotime($start[1]));
$end[1] = date("h:i:s A", strtotime($end[1]));
}
echo "<tr>
<th>" . $row['date'] . "</th>
<th>" . $start[1] . "</th>
<th>" . $end[1] . "</th>
<th>" . $row['total'] . "</th>
</tr>";
}
foreach ($conn->query($sql4) as $row) {
echo "<tr>
<th></th>
<th></th>
<th>SUM</th>
<th>". $row['SUM(total)'] . "</th>
</tr>";
}
echo "</table>";
you can do it with the TIME function:
$sql4 = "SELECT TIME(SUM(total)) AS totalSum FROM timeSheet WHERE userName='$user_name'";
//....
foreach ($conn->query($sql4) as $row) {
echo "<tr>
<th></th>
<th></th>
<th>SUM</th>
<th>". $row['totalSum'] . "</th>
</tr>";
}
hint:
actually you don't need the total column in your database. You can use i.e
SELECT date, startTime, endTime, TIMEDIFF(startTime, endTime) AS total FROM timeSheet WHERE userName='$user_name'"
and
SELECT TIME(SUM(TIMEDIFF(startTime, endTime))) AS totalSum FROM timeSheet WHERE userName='$user_name'
for further information have a look at: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff

How to calculate total number of entries per state using mysql and php

I have a table "data" with a column "name" "state" and a few more
name state
peter MN
john NY
jay NY
sam CO
jack TX
jill NO
I want to calculate the number of entries per state and want my output as follows for example:
NY: 125
MN: 21
CO: 17
TX: 10
NO: 59
etc...
I have a query like this
$stmt = $db->query("SELECT state, COUNT(*) FROM `data` GROUP BY state;");
$nums = $stmt->rowCount();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>
<td>" . $row["state"] . "</td>
<td>$nums</td>
</tr>";
}
This displays every state in my table but does not return the corresponding number of entries for that state. This only returns the number of states i.e. 50. How can I display the number of entries per state?
You seem not to be referring to the column which has the count. Try aliasing it an referencing the alias in your PHP code:
$stmt = $db->query("SELECT state, COUNT(*) cnt FROM `data` GROUP BY state;");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>
<td>" . $row["state"] . ":</td>
<td>" . $row["cnt"] . "</td>
</tr>";
}
$stmt = $db->query("SELECT COUNT(name) as occurances,state FROM `data` GROUP BY state;");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>
<td>" . $row["occurances"] . "</td>
<td>" . $row["state"] . "</td>
</tr>";
}
Try this version,select the names only

Selecting row information by date

I'm trying to display data starting at a certain time and day and ending and another time and day. here is my code:
<?php
include 'includes/connect3.php';
$query = "SELECT * FROM u_visits WHERE date >= '2013-08-31 22:56:20' AND date <= '2013-
08- 31 23:59:59'";
$result = mysqli_query($con,$query);
echo "<table><tr>
<th>USER ID</th>
<th>TIMES VISITED</th>
</tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['visits'] . "</td></tr>";
}
echo "</table>";
?>
When I go to the page, only the table header is displayed with no data showing.
you can also use BETWEEN for range comparisons.
$query = "SELECT * FROM u_visits WHERE `date` BETWEEN '2013-08-31 22:56:20' AND '2013-08-31 23:59:59'";
The reason you didn't see any result is because your query has some errors. The error in your query is that you have a space after 2013-08- in your where clause (date <= '2013-08- 31 23:59:59'";)
Had you used proper error handling, you would have noticed this yourself. One common way to do this is:
$result = mysqli_query($con,$query) or die ('Query execution failed: ' . mysqli_error($con));

php mysql select from columns from 2 tables Join

I have two tables.
visitors_details, with id,scanner_id,time columns
and visitors_info with scanner_id, name,surname columns
I want to get back
id,name,surname,time in a table
i have written this but is not working
$result = mysql_query("SELECT visitors_details.id AS id,
visitors_info.name AS name, visitors_info.surname AS surname, visitors_details.time
AS time FROM visitors_details AS d LEFT JOIN visitors_info AS i ON
d.scanner_id=i.scanner_id ");
echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>surname</th>
<th>Time</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['time'] . "</td>";
echo "</tr>";
}
echo "</table>";
any ideas??
Its better to enable some debugging for your code like this:
<?php
error_reporting(E_ALL);
$sql = "
SELECT d.id AS id, i.name AS name, i.surname AS surname, d.time AS time
FROM visitors_details AS d
LEFT JOIN visitors_info AS i ON d.scanner_id=i.scanner_id
";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
try this query
$result = mysql_query("SELECT d.id , i.name , i.surname , d.time
FROM visitors_details AS d LEFT JOIN visitors_info AS i
ON d.scanner_id=i.scanner_id ");
Add this to catch errors. saves a lot of time:
if(!$result) {
echo mysql_error();
}

Categories