I have a PHP query to display the time an order was inserted on the database but all I'm getting in return is the current time not what I have on the database table.
public function count_todayorder(){
$today_date = date("m-d-Y");
$query="SELECT * FROM set_order_detail WHERE order_placed_date LIKE '%$today_date%'";
$con=Utility::DB_Connection();
mysqli_set_charset($con,'utf8');
$result=mysqli_query($con,$query);
$count=mysqli_num_rows($result);
return $count;
}
To display the table I'm using this.
<div>
<b>Ordered date:</b>
<?php date_default_timezone_set('America/New_York');
echo $today_date = date('g:i:s A - m-d-y ');
?>
</div>
It seems you are not actually using the date from the database, but rather you are just using the date function without setting the timestamp.
This is the date() functions syntax: date(format,timestamp);
So using your code, it would be:
date('g:i:s A - m-d-y ', $dateFromDB);
You just need to get the date from the database, and add it to the date() function where $dateFromDB is.
Try to change this date formate
Database date formate is yyyy-mm-dd.
So you should change your current date formate like below:
$today_date = date("Y-m-d");
$query='SELECT * FROM set_order_detail WHERE order_placed_date LIKE "%'.$today_date.'%"';
To tackle the problem you need to firstly understand that you have 2 different servers. One for the PHP and one for the database-in your case MySQL. Latter server will store records based on the time_zone stored variable. By default that should be set to SYSTEM -if you haven't tempered with the settings.
To check that perform the following query SELECT ##time_zone;. In case that it is something like +00:00 it is equal to GMT. Alternatively try SHOW VARIABLES LIKE 'time_zone';
Thus, for integrity purposes, you should always rely on what your SQL server provides. Lets amend the select statement to;
$query="SELECT * FROM `set_order_detail` WHERE DATE( `order_placed_date` ) = DATE( NOW( ) )";
...and remove the $today_date = date("m-d-Y"); part which, is not needed at all.
I assume that order_placed_date is either DATETIME or TIMESTAMP since you haven't placed a data-set example.
Given query will return the date format which by default is 'YYYY-MM-DD'. Casting this into PHP via date function will re-evaluate it based on the PHP server clock, which is a non-go. To get the proper format you need something like this
SELECT *, DATE_FORMAT( `order_placed_date`, '%l:%i:%s %p - %c-%e-%y') AS `format` FROM `set_order_detail` WHERE DATE( `order_placed_date` ) = DATE( NOW( ) );
Please check MySQL DATE_FORMAT function for more details.
To continue, your function -like #Barmar wrote in a comment- returns the number of rows matched and not the content fetched via the query. Therefore, the function should look something like that.
// somewhere in your class add this
public function todayOrders( )
{
$query="SELECT *, DATE_FORMAT( `order_placed_date`, '%l:%i:%s %p - %c-%e-%y') AS `format` FROM `set_order_detail` WHERE DATE( `order_placed_date` ) = DATE( NOW( ) );";
$con=Utility::DB_Connection();
mysqli_set_charset($con,'utf8');
$result=mysqli_query($con,$query);
if( !is_resource( $result ) )
{
return [];
}
$rows = [];
while( $row = mysqli_fetch_row( $result ) )
{
$rows[ ] = $row['format'];
}
return $rows;
}
Note: do not replace your previous method, just append this one, in case there are errors on this method. I am not able to test it atm.
To conclude and to produce the set of results fetched via the db in your template try the following.
<?php $rows = todayOrders( ); ?>
<?php foreach( $rows as $today_date ) : ?>
<div>
<b>Ordered date:</b> <?php echo $today_date; ?>
</div>
Hope it helped.
Related
I have in my MSSQL database a column with datatype of datetime which contains some dates in this format 2021-01-11 19:58:04.277.
This is a voting system, the idea is that the users can only vote once every 24 hours.
Every time they vote this table is updated with a new record and a new date is added with the corresponding user.
I want to display a message that says how many hours left to place the next vote.
This is the code I am trying to use:
/**
* Get Votes Time
*
*/
public function getVoteRemainingTime($account) {
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$sql = "SELECT VoteDate FROM dbo.vote WHERE Account = :account ORDER BY logid DESC";
$query = $this->db->prepare($sql);
$query->execute(array(':account' => $account));
$voteDate = $query->fetch(PDO::FETCH_OBJ);
$timeLeftVote = strtotime($currentTime) - strtotime($voteDate->VoteDate);
if($timeLeftVote > 86400) {
return '<strong>Vote Available!</strong>';
} else {
return $timeLeftVote;
}
}
But it is displaying the wrong information. What I am doing wrong? I would appreciate your help.
Thanks!
you need declare format parameter of the date() like date('Y-m-d H:i:s')
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$timeLeftVote = strtotime($currentTime) - strtotime('2021-01-11 19:58:04.277');
if($timeLeftVote > 86400){
echo 'Vote available';
}else{
echo $timeLeftVote;
}
Instead of SELECT VoteDate FROM dbo.vote
Can you do the calculation on the time difference at source in the database using
SELECT VoteDate, DATEDIFF(HOUR, VoteDate, GETDATE()) as HourDifference from dbo.vote
As I cannot check your database query, I only checked the rest of the code and it seems to work (as Fikri F mentioned in the comments of this post) if I replace $voteDate->VoteDate by a static date.
So please provide more information. You could output the current time and the previous vote time from the database as strings, and for both dates as well the result of strtotime, and in the end the result of the method. Then please explain, what the wrong behaviour is. By this, we can narrow down the problem either to the DB query or to the PHP code.
(I would write this as a comment, but I have not enough reputation.)
I'm trying to get a datetime value from MySQL table. I stored it like 'yyyy-mm-dd hh:mm:ss', but when I want to get it to print in a page, I get this '2019-04-01 00:00:00' or only '2019-04-01'. If I check the database, I can see the time stored properly, but when I want to print it, I only get zeros.
if( $stmt = $mysqli->prepare( '
SELECT
estadistica_id,
aprobados,
suspendidos,
pendientes,
envios,
fecha,
curso.curso_id,
identificador_envio,
curso.titulo AS titulo_curso
FROM estadistica
LEFT JOIN curso ON estadistica.curso_id = curso.curso_id
ORDER BY titulo_curso ASC' . $order_by
) ) {
if( true === $stmt->execute() ) {
$stmt->store_result();
$stmt->bind_result(
$estadistica_id,
$aprobados,
$suspendidos,
$pendientes,
$envios,
$fecha,
$curso_id,
$identificador_envio,
$titulo_curso
);
if( ( $num_rows = $stmt->num_rows ) > 0 ) {
while( $stmt->fetch() ) {
echo $fecha;
}
}
$stmt->free_result();
$stmt->close();
}
}
$fecha prints '2019-04-01' and nothing more. I don't know how to print the date and time stored in the database.
Here goes the screenshots of the database, where you can see that the date and time is stored correctly.
I'm lost :(
Appreciate all your help ;)
When fetching a datetime value from database, the default format depends on your client. Most clients use MySQL default format ('YYYY-MM-DD HH24:MI:SS'), but it looks like yours doesn't.
One solution would be to turn the date to a string with the expected format within the SQL query, using MySQL function DATE_FORMAT():
Consider:
SELECT
estadistica_id,
...,
DATE_FORMAT(fecha, '%Y-%m-%d %H:%i:%s'),
...
FROM estadistica
...
As R.Smith said in his comment, it should work if your column's format is varchar. You must have another one.
You can use DateTime (https://www.php.net/manual/en/class.datetime.php)
Example :
$date = new \DateTime($fecha);
echo $date->format('Y-m-d H:i:s');
// => 2019-04-01 18:42:03
I'm new to using the convert function. I'm trying to make a datetime value from my table shorter. Currently my datetime values look something like this, 2016-10-14 16:51:41, but I'd like to make it look something like mm/dd/yy.
I don't know if this is the right approach (must not be since it doesn't work), but I've generated a query using the convert function and then fetching the data with a mysqli_fetch_array.
Here's the code I'm using:
$sql = "SELECT id, time, CONVERT(VARCHAR(11), time) as something FROM tableName";
$query = mysqli_query($db, $sql);
$statusnumrows = mysqli_num_rows($query);
// Gather data about parent pm's
if($statusnumrows > 0){
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$time= $row["time"];
}
}
Time is the name of the column which has the datetime type.
Thanks in advance, for suggestions/advice.
You should store datetime in your DB in proper data types like datetime etc.
As I can see you are using PHP, if you need to OUTPUT this datetime in some interface (f.e. HTML page), you should use PHP functions to convert date in format you need. That is the good practice
DB should STORE the data but formatting is front-end problem.
Simple example of strtotime() and date():
$Date = "2016-10-15";
$newDate = date("m/d/Y", strtotime($Date));
You can read docs on the PHP site: strtotime and date
If 2012+ you could use format (not very efficient but does offer some other possibilities)
Declare #Date DateTime = GetDate()
Select UsingFormat = Format(#Date,'MM/dd/yy')
,UsingConvert1 = convert(varchar(10),#Date,1)
,UsingConvert101 = convert(varchar(10),#Date,101)
Returns
UsingFormat UsingConvert1 UsingConvert101
10/15/16 10/15/16 10/15/2016
Use style 1 in Convert function for mm/dd/yy format
select CONVERT(VARCHAR(20), [time],1)
From yourtable
If you want mm/dd/yyyy format then use 101 style
select CONVERT(VARCHAR(20), [time],101)
From yourtable
MSDN link for Convert function with various style : CONVERT
i'm saving time for first login ,now when user logs in i enter time using NOW() function, that saves time in this format (data type is DATETIME.
2015-12-24 15:47:30
Now logic is like every login is first login so i've to check if there already exists an entry for today to check that i fetch time explode it and get time like this
$logintime= mysqli_query($connection,"SELECT loggedin from employees");
$loggedin_time= mysqli_fetch_assoc($logintime);
$Date = $loggedin_time['loggedin'];
$loggedin_time_converted= explode(" ",$yourDate) ;
$ConvertedDate = $loggedin_time_converted[0];
last line returns 2015-12-24 now i've date
$today= time();
$DateToday= date("Y-m-d",$today);
$DateToday also returns me same format and same date now i need your help me to compare these dates , if they are equel i dont uopdate database if they are not i will , Pleas help me how do i compare these values
You can do the test in MySQL
$result = mysqli_query($connection, "SELECT DATE(loggedin) = CURDATE() AS logged_in_today FROM employees");
$row = mysqli_fetch_assoc($result);
if (!$row['logged_in_today']) {
// code to update database
}
Wow, you've done all the hard stuff to get the problem to the point of being a simple comparison of 2 strings. This is all you need to do to get over the finish line ...
if ($ConvertedDate !== $DateToday) {
// update the database
}
You can use Php Built In function "Date Difference."
Code Seems Like As Follow:-
$today= time();
$DateToday= date("Y-m-d",$today);
$diff = date_diff($today,$DateToday);
echo "$diff days";
This will return values something like +12 days or something else.
Trying to figure out why my code isn't working. Basically I have an elseif statment like so:
mysql_connect("localhost","xxxx","xxxxx");
mysql_select_db("xxxxxx");
$sql = "SELECT COUNT(DATE) FROM calendar";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$checkdate = $row['DATE'];
$DATEFROM = $_POST['DATEFROM'];
$DAYCOUNT = $_POST['DAYCOUNT'];
$DAYS = $_POST['DAYS'];
if ( $DAYCOUNT < $DAYS ) {
header( 'Location: request_go_fail.php' );
}
else if ( $checkdate == $DATEFROM ) {
echo "FAIL!";
}
else {
It doesn't work, the first check (to see if the DAYCOUNT is less than DAYS works fine, but when comparing to entries in the DB it doesn't seem to do it. Seems to be some issue with finding the already existing data, as when I change $checkdate to an entry that's already in the database it works great.
Any help is most appreciated :)
SELECT COUNT(DATE) FROM calendar doesn't return a field called date, print_r the $row variable to confirm that. Best solution is to change the statement to something like SELECT COUNT(DATE) AS datecount FROM calendar and then do $checkdate = $row['datecount'];
But while rereading your code fragment, I'm not sure that you really want the count of DATE's in the calendar table, and what exactly the intention is, is hard to determine from the code fragment.
Also, DATE is a reserved word in SQL, not the optimal choice for a column name!
Did you try printing $checkdate? I suspect it's null if that is indeed the SQL you're using.
Should be $row['COUNT(DATE)'] I believe, or you can use mysql_fetch_array and $row[0] instead, or use an AS in your SQL or
$checkdate = mysql_result($result, 0);
And skip the fetch call all together.
COUNT(DATE) will return the number of non-null DATE fields in your DB btw, is that really what you want?
You don't have a DATE key in the $row variable because of the sql command. Use this instead, it's called Alias:
SELECT COUNT(DATE) AS DATE_COUNT FROM calendar
Now you have a key DATE_COUNT which will contains value.
$checkdate = $row['DATE_COUNT'];