MySQL Date_Format isn't working with - php

I have a PHP page with a MySQL database with 2 fields that use the TIME type in MySQL. I want to convert those two fields from the 24 hour format (00:00:00) into 12 hour AM/PM format (00:00 AM) using MySQL's DATE_FORMAT('','') but it's not working.
So far, what I have done is created a 3rd and 4th field that also uses the TIME type. I send the 1st and 2nd field into the 3rd and 4th and convert the 3rd and 4th to preserve the original.
<?php
//connection statements omitted
$sql="SELECT * FROM $table ORDER BY date LIMIT $start, $amount";
$result = $mysqli->query($sql);
//Sends the original time_in data to the new format_in column.
$sql2="UPDATE $table SET format_in = time_in";
$result2=$mysqli->query($sql2);
$sql3="SELECT DATE_FORMAT(format_in,'%l:%i %p') FROM $table";
$result3=$mysqli->query($sql3);
while($row = $result->fetch_array()){
?>
//other fields omitted
<td><?php echo $row['format_in'];?></td>
//end while loop
<?php } ?>
The only thing this code does is replicates whatever was in the time_in column. Which is the standard 24 hour format 00:00:00. Basically, this code doesn't do anything. What am I doing wrong here?
EDITED to show my $result

while($row = $result3->fetch_array()){
instead of
while($row = $result->fetch_array()){
Based on the conversation we had in comments section:
Change
$sql="SELECT * FROM $table ORDER BY date LIMIT $start, $amount";
$result = $mysqli->query($sql);
to
$sql="SELECT field_1,field_2,field_n,DATE_FORMAT(format_in,'%l:%i %p') format_in FROM $table ORDER BY date LIMIT $start, $amount";
$result = $mysqli->query($sql);

Related

How to Subtract current date time from date time in database - PHP

I'm working on a project.I have to check " how many minutes ago ,user updated the database " .For that I used following code :
<?php
include('connect_db.php');
$sql =" SELECT * FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$time = strtotime($row['time_']);
$current=time();
$sub_time=$current-$time;
echo $sub_time;
}
The problem is the code is returning negative values like [ -17173 ].
The date-time stored in my db is like [ 2018-07-14 11:42:21.006515 ]
I simply want to compare current time with the the time stored in database get results in seconds or minutes .
I need help to solve this issue.Thank you .
You can just change your select statement to give you the time difference in seconds as shown below:
$sql =" select UNIX_TIMESTAMP(current_Timestamp()) - UNIX_TIMESTAMP(time_) FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;
I think DateTime is better approach, as it has the methods to achieve the result you need.
maybe something like this:
$time=$row['time_'];
$curr_time=new DateTime();
$difference=$time->diff($curr_time);
http://php.net/manual/en/class.datetime.php
Updated
You should use the DateTime functions to figure out the difference in time. You should be able to integrate this into your code.
I incorporated my suggested code as a function into your original code. This should work for you.
Try this:
function timeDiff($date){
$date = new DateTime(date('Y-m-d H:i:s', strtotime($date)));
$current = new DateTime(date('Y-m-d H:i:s'));
$interval = $date->diff($current);
return $interval->format('%H:%I:%S');
}
include('connect_db.php');
$sql ="SELECT * FROM test_table WHERE user='john' ORDER BY time_ DESC LIMIT 1" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo timeDiff($row['time_']);
}
}
You first need to convert them to timestamp. And them subtract them convert the resuting timestamp back to format you want.
while($row = $result->fetch_assoc()) {
$time = strtotime($row['time_']);
$current=time();
$sub_time=date('d-m-y h:i:s',(strototime(date('d-m-y h:i:s')-$time));
echo $sub_time;
}
You need to handle the greater than and less than cases too.

Get date and time of max value

I have a weather-reading database where I store all data for consumption by a webpage that shows the MAX and MIN pressure.
The problem is that I like to show the time and date in which these values where recorded.
Code I use to read MAX pressure:
$max_out_pressure = mysql_query("SELECT MAX(out_pressure) AS out_pressure FROM $table");
$max_out_pressure = mysql_result($max_out_pressure,0,"out_pressure");
$max_out_pressure = substr($max_out_pressure, 0, 6);
echo "$max_out_pressure";
echo "mbar";
I have the columns ID, Datetime, Pressure, Temperature
Table is named readings
Webpage: http://temperatur.co.nf/readings.php
Never made an database or webpage before, so I`m struggling with this.
This will get the maximum pressure and the date it was recorded.
$sql = "SELECT out_pressure, Datetime
FROM $table
ORDER BY out_pressure DESC
LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$max_out_pressure = $row['out_pressure'];
$max_date = $row['Datetime'];

finding the data from database whose field is in datetime datatype

I have used the following code to get the data of the field having it's datatype datetime but it executed the result as empty set. Please help me to solve it.
mysql_query("set #last_day=last_day(now()-interval 1 month),#first_day=(#last_day-interval 1 month)+interval 1 day");
$result=mysql_query("select * from `gcm_users` where (`created_at` between #first_day and #last_day)") or die("could not fire the query");
while($row=mysql_fetch_assoc($result))
{
echo $row['created_at'];
exit;
}
the created_at field has datetime datatype.
You can't do two queries like that, one to set variables and another to use them. This isn't a stored procedure.
Do it by using PHP variables and concatenating:
$last_day = "last_day(now()-interval 1 month)";
$first_day = "({$last_day}-interval 1 month)+interval 1 day)";
$sql = "select * from `gcm_users` where (`created_at` between {$first_day} and {$last_day})"
$result = mysql_query($sql) or die("could not fire the query");

How to display table data by today's date?

I have a database called gameschedules and a table called dec1212. Inside of this table are the columns date (YYYY-MM-DD), division, field, time, team1, and team2 in that order.
I already have the data displaying on my page but I need to restrict it to only showing rows in my database that have a date that is equal to the current date. So if there are 10 rows and only 5 of them have today's date in the date column, only those should show. Here is my current query code and I know it is wrong but if someone can help me correct it that would be great:
Current code:
//specifies that it is getting data from the table and limited num rows
$result = mysql_query("SELECT * FROM `dec1212` LIMIT 0, 10 ") or die(mysql_error());
This is what I tried to do to restrict data by date:
//set variable to current date with same format as date column
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM 'dec1212' WHERE date = $myDate()") or die(mysql_error());
I know that my code is incorrect so this is why I am asking for help.
Try this just a signal line query
$result = mysql_query('SELECT * FROM dec1212 WHERE DATE(CONVERT_TZ(date,"+00:00","-8.00")) = DATE(CONVERT_TZ(UTC_TIMESTAMP(),"+00:00","-8.00"))') or die(mysql_error());**
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM `dec1212` WHERE date = '$myDate'") or die(mysql_error());
Try this
$result = mysql_query("SELECT * FROM `dec1212` WHERE `date` = CURDATE()") or die(mysql_error());
Try This
//set variable to current date with same format as date column
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM 'dec1212' WHERE date = $myDate") or die(mysql_error());
You are using variable not the function so just change like this
$myDate = date('Y-m-d');
$result = mysql_query("SELECT * FROM 'dec1212' WHERE date = '$myDate'") or die(mysql_error());
Make sure your date field in database containing the only date, not time
$result = mysql_query("SELECT * FROM 'dec1212'
WHERE `date`= '$myDate'") or die(mysql_error());
if your date field containing datetime datatype then use:
$result = mysql_query("SELECT * FROM 'dec1212'
WHERE `date`= date('$myDate')") or die(mysql_error());
Let the database do the work,
SELECT * FROM `dec1212` WHERE DATE(date) = DATE(NOW())
Note that $myDate is a variable, not a function. Thus, your code would be :
//set variable to current date with same format as date column
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM `dec1212` WHERE date = '$myDate'") or die(mysql_error());
Table name or field name should be wrapped with carat `, not single quote ' or you may omit it.
If you want to use MySQL NOW(), you need to consider time zone conversion as Raj Mohan mentioned.

Having trouble with MySQL double to date conversion

I have searched and searched for ways to do this but have found very limited information.
I have a MySQL table 'msgdb' that contains a field 'ttime' that is in the format double(25,8) (example row = 1352899856.95249200).
I need to routinely cleanup the table by removing any rows where the field 'ttime' is <= today's date -5 days.
These are the only two lines of code I could find related to double to time conversion but cannot get either to work.
SELECT ADDDATE(ADDDATE(ADDDATE('1899-12-31 00:00:00',FLOOR(ttime)), INTERVAL -1 DAY),INTERVAL(MOD(ttime,1)*86400)SECOND) AS TrueDate FROM msgdb
select date('1899-12-31 00:00:00'+ INTERVAL ttime * 24*3600 SECOND) as date from msgdb
I have tried first to display any rows that match the criteria using the code below, before I started using DELETE FROM to make sure I'm getting the correct results.
$query = "select date('1899-12-31 00:00:00'+ INTERVAL ttime * 24*3600 SECOND) as date from msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo $row['date'];
echo '<br>';
}
and also
$query = "SELECT ADDDATE(ADDDATE(ADDDATE('1899-12-31 00:00:00',FLOOR(ttime)), INTERVAL -1 DAY),INTERVAL(MOD(ttime,1)*86400)SECOND) AS TrueDate FROM msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo $row['TrueDate'];
echo '<br>';
}
but both are returning nothing.
UPDATE: Ok so by using this code:
$query = "select ttime from msgdb";
$result = mysql_db_query ($dbname, $query, $link);
while($row = mysql_fetch_array($result)) {
echo date('m-j-Y, H:i:s', $row[0]);
echo '<br>';
}
I am able to see it convert 'ttime' field from the stored value of 1352899856.95249200 to 11-14-2012, 07:30:56.
So how would I DELETE from the table all rows where ttime is <=now - 5 days?
Figuring out which records have a date before a point in time should be easy:
DELETE FROM table WHERE ttime <= DATE_SUB(NOW(), INTERVAL 5 DAY);
It might also be better to use UTC_TIMESTAMP() if you store all your times in UTC, which is the only sane way to do it.

Categories