I got the following problem. I got a mysql field which is type "text" and there are many birthday dates in it.
I want to print the dates out and sort it in my way of date format. I can't change the type in the database because it's related to some user profile value fields.
The value's thats in the database are such this:
1978-12-31 23:59:59
This is my query:
$result = mysql_query("SELECT a.value, b.username from yrt6h_community_fields_values a join yrt6h_users b on a.user_id = b.id where a.field_id = 3 order by a.value;");
And this my example php file:
<table>
<tr>
<td>User:</td>
<td>Datum:</td>
</tr>
<?php
while($row = mysql_fetch_array($result)){
echo '<tr>';
echo '<td>';
echo $row['username'] . ' : ';
echo '</td>';
echo '<td>';
echo $row['value'];
echo '</td></tr>';
}
?>
</table>
I tried all of the date format functions of mysql, but then i got nothing.
For example I tried this:
mysql_query("SELECT str_to_date(a.value, '%d.%m.%Y'), ...
or
mysql_query("SELECT str_to_date(date_format(a.value, '%Y.%m.%d') %d.%m.%Y), ...
But I do that, the echo of the date is empty. Theres nothing to print out anymore. But why? Even if I put this query directly in the database I got NULL for the birthday value.
why dont you try to do it with php like -
echo date('d-m-Y', strtotime($yourDate));//the first paramete is the date format you want and the second is the value you are getting from database.
Reference for more understanding, example and formats.
Almost there!
I would suggest that you first get the data from the db with
mysql_query("SELECT str_to_date(a.value, '%d.%m.%Y')
Then
while($row = mysql_fetch_array($result))
{
$date = $row['date'];
$time = strtotime($date);
$formattedDate = date('Y-m-d', $time);
}
echo $formattedDate ;
Does that make senese?
Have you tried the PHP Date() function?
You could do something like so:
If you're looking for all records that match a specific date:
$timestamp = date('Y-m-d H:i:s'); //get current timestamp
mysql_query("SELECT * FROM `table` WHERE `timestamp` = '$timestamp'");
Or -- If you're trying to select/order by Timestamp:
mysql_query("SELECT * FROM `table` ORDER BY `timestamp`"); //select all order by timestamp
you can use mysql "cast" function.
rewrite the query in such a way:
"SELECT cast(a.value as DATETIME) new_dob,str_to_date(a.value, '%d.%m.%Y') dob from table_nm where cond"
Related
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.
I am displaying a list of months and years from the database like this into a drop-down menu:
$stmt = $link->prepare("SELECT `b_date` FROM `summary` GROUP BY YEAR(`b_date`), MONTH(`b_date`)");
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
while($row = $result->fetch_assoc()) {
$month = date('F Y', strtotime($row['b_date']));
echo "<option value='{$month}'>{$month}</option>";
}
}
When the user clicks on a choice, it redirects to another page like:
mypage.com/results.php?date=
The problem is that I don't know what to set the value as. In the current code the url produced looks like:
php?date=April%202017
That obviously isn't ideal. And the point is that on the results page I need to show results for the month that was selected. So, I need that query string to query the database.
You can put to select value something like 05-2017:
while($row = $result->fetch_assoc()) {
$month = date('m-Y', strtotime($row['b_date']));
echo "<option value='{$month}'>{$month}</option>";
}
And then get it with DateTime object:
$date = DateTime::createFromFormat('m-Y', $_GET['date']);
And then you can format this object to any format you want:
$formated_date = $date->format('Y-m-d');
You can chose another format, but I think you understand my idea.
UPD. To execute all record on this month try to use this code:
$date = DateTime::createFromFormat('m-Y', $_GET['date']);
$stmt = $link->prepare("SELECT * FROM `summary` WHERE YEAR(`b_date`) = :year AND MONTH(`b_date`) = :month");
$stmt->bindParam(':month', $date->format('m'));
$stmt->bindParam(':year', $date->format('Y'));
$stmt->execute();
$result = $stmt->get_result();
I think its working but maybe need to fix.
Change like this (use urlencode()):-
$month = date('m-Y', strtotime($row['b_date']));
echo "<option value='".urlencode($month)."'>{$month}</option>";
Now on next page check $_GET['date'] and see it's coming proper or not?
if it come proper in format like m-Y then split it with - and now you get month and year separately. Use them in your query or wherever you want.
Query need to be like something:-
$_GET['date'] = '04-2017';
$date_array = explode('-',$_GET['date']);
$month = $date_array[0];
$year = $date_array[1];
"SELECT * FROM summary WHERE MONTH(<you date column name>) = $month";
U can format data in select (postgres, mysql...)
SELECT TO_CHAR('MM-YYYY', b_date) AS formated_date FROM summary GROUP BY TO_CHAR('MM-YYYY', b_date
Sorry my English a little,
My date column is 1375801584 valuable epoch format.
I wanna only select now and next time records, i want hide history times record.
eg: 19:45 and later.
<?php
$sql = mysql_query("select tarih from table where tarih < '$date' order by tarih ASC");
while($r = mysql_fetch_assoc($sql)){
?>
<tr><td><?php echo date("Y-m-d", $r['tarih']); ?></td>
<td><?php echo date("H:i", $r['tarih']); ?></td></tr>
<?php
}
?>
You close. Your current query is selecting older records (<). Try using >=:
$sql = mysql_query("select date from table where date >= '$date;' order by date ASC");
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.
I am using mysql and php to pull all the users out of the mysql database that are equal to todays date. The problem I am having is whenever I run the following code I get an error. By the look of the error is seems to be something to do with the year, or maybe it doesn't like the dots in it, but im not sure ?.
<?php
$today = date("d.m.y");
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE date=$today")or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['name'] . " " . $row['email']. " " . $row['date'];
echo "<br />";
}
?>
This is the error it is throwing :
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '.12' at line 2
You have to add quotes around your date string:
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE date='$today'")or die(mysql_error());
Need quotes around your $today variable. Also need to backtick the date column name since it's reserved.
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE `date`='$today'")or die(mysql_error());
First of all, $today should be added as a string into the SQL query:
mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` = '$today'");
date is a SQL reserved word so it has to be escaped with backticks...
But I recomment using MySQL native functions and constants like NOW(), CURRENT_TIMESTAMP, SYSDATE etc...
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` = NOW()
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` < NOW() - INTERVAL '2' DAYS
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE `date` > NOW() + INTERVAL '5' HOURS
etc...
if you are using timestamp as datatype in mysql then you need to convert the date into unix timestamp first.
$today = strtotime("now");
or if you are using datetime or date data type then correct format is
YY-MM-DD, so you need to create the date accordingly.
$today = ('Y-m-d');
and also in your query you are missing single quote.
"SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE date = '$today'"
however you can compare the date without using PHP's date function, directly using MYSQL NOW().
SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe WHERE date = NOW()
Try
$today = date("d-m-Y");
OR
$today = date("Y-m-d");
Also, check the format of date column is equal to the format of the return value of date().
If you have used DATETIME data type you may need to use matching format.
Also, wrap date value with single quotes...
$result = mysql_query("SELECT * FROM ymeg_chronoforms_data_NewsletterSubscribe
WHERE date = '" . $today . "'")