I've made a query that calculates the total_time1
from 2 other fields called time_in
and time_out
using timediff(time_out, time_in) AS total_time1
.
Now, I want to convert that time into a better format instead of the usual hh:mm:ss
so in the same query I did DATE_FORMAT(total_time1, '%l:%i') AS total_time2
, but for some reason it doesn't work whenever I input a new time in and out.
This is the query:
$sql="SELECT
DATE_FORMAT(time_in, '%l:%i %p') AS time_in,
DATE_FORMAT(time_out, '%l:%i %p') AS time_out,
timediff(time_out, time_in) AS total_time1,
DATE_FORMAT(total_time1, '%l:%i') AS total_time2,
FROM $table";
$result = $mysqli->query($sql);
while($row = $result->fetch_array()){
<td><?php echo $row['time_in']; ?></td>
<td><?php echo $row['time_out']; ?></td>
<td><?php echo $row['total_time1']; ?></td>
<td><?php echo $row['total_time2']; ?></td>
}
I'm displaying everything (including time in, out, totaltime1 and totaltime2) on a large table on it's own page. total_time1
works like I said, but total_time2
displays nothing. No errors or anything. What am I doing wrong here.
You can't use an alias you made in the same query
you have to write it again like this
$sql="SELECT
DATE_FORMAT(time_in, '%l:%i %p') AS time_in,
DATE_FORMAT(time_out, '%l:%i %p') AS time_out,
timediff(time_out, time_in) AS total_time1,
DATE_FORMAT(timediff(time_out, time_in), '%l:%i') AS total_time2
FROM $table";
Also, if you want to format time,
you should not use DATE_FORMAT
but TIME_FORMAT
instead
like this
$sql="SELECT
TIME_FORMAT(time_in, '%l:%i %p') AS time_in,
TIME_FORMAT(time_out, '%l:%i %p') AS time_out,
timediff(time_out, time_in) AS total_time1,
TIME_FORMAT(timediff(time_out, time_in), '%l:%i') AS total_time2
FROM $table";
Here's the documentation about all the date and time functions in MySQL
You can't self-reference the column. You also had an extra comma, which I assume was a typo.
You need something like this:
$sql="SELECT time_in, time_out, total_time1, DATE_FORMAT(total_time1, '%l:%i') AS total_time2
FROM (SELECT
DATE_FORMAT(time_in, '%l:%i %p') AS time_in,
DATE_FORMAT(time_out, '%l:%i %p') AS time_out,
timediff(time_out, time_in) AS total_time1
FROM $table) a";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.