Get datetime field value from MySQL database - php

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

Related

PHP MySql query shows current time instead of the time from tablet

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.

mysql timestamp output as formatted Date not working

I have a crazy phenomenon in my php script. I have defined a column as a timestamp in a mysql table. I fill it with the function:
date("Y-m-d H:i:s");
The data in the table then look like this: 2017-04-19 17:08:45
When I query this column with mysqli as a unix timestamp again:
SELECT UNIX_TIMESTAMP (timestamp) as timestampUnix FROM posts
Then binding the result using bind_result to the variable $timestampUnix.
I can echo the variable with
echo $timestampUnix;
and it outputs a correct timestamp like this: 1492614559
however if i do the following:
$timestampUnix2 = $timestampUnix;
echo $timestampUnix2;
there is simply no echo output... What is the reason?
I tried this because I actually want echo only the date in an other format with:
date('d.m.Y', $timestampUnix)
and it gave me 01.01.1970 and i wondered why the timestamp must be 0 but it isnt since when i directly echo it it gives me a correct one.
however when i do
Date('d.m.Y', 1492614559)
it gives me the correct date.. no clue what is going on there!
i know there are many other questions about mysql php Date output, but no one have this issue as i think i cannot do something with the variable i got from the query.
thanks in advance!
edit: i attach the complete code in question:
---the query that inputs the data in the db----
$timestamp = date("Y-m-d H:i:s");
mysqli_query($mysqli,"INSERT INTO posts (timestamp)
VALUES ('$timestamp')");
---the query that fetches the data----
$results = $mysqli->prepare("SELECT UNIX_TIMESTAMP(timestamp) as timestampUnix FROM posts");
$results->execute(); //Execute prepared Query
$results->bind_result($timestampUnix); //bind variables to prepared statement
$postdate = date('d.m.Y',$timestampUnix)
echo $postdate;

Query between two dates with MySQL

I am trying to get all rows in a database which have been created between two dates inclusively. When I search for meetings in 2013-05-01 and todays date, I get no results but when I search without the WHERE clause I see there are two records for today. I thought, since the dates are DATETIME, I would try casting them as dates but this doesn't seem to work.
My function is as follows:
function meeting_reports($connection, $to, $from)
{
$status = array();
$sql =
$connection->query (
"SELECT `meeting_id`,`visibility`,`meeting_start`
FROM `details`
WHERE DATE(`meeting_start`) BETWEEN '{$from}' AND '{$to}'"
);
$status["total_meetings"] = 0;
$status["cancelled_meetings"] = 0;
if($sql->num_rows > 0)
{
while($results = $sql->fetch_assoc())
{
if($results["visibility"]==0)
{
$status["total_meetings"]++;
}
elseif($results==1)
{
$status["total_meetings"]++;
}
elseif($results["visibility"]==2)
{
$status["total_meetings"]++;
}
elseif($results["visibility"]==3)
{
$status["cancelled_meetings"]++;
}
}
}
return $status;
}
What am I doing wrong?
I see a couple issues here.
you need to clarify if your data type is date, or datetime. going to assume datetime.
also if you are looking for meetings that occurred on a single specific day,
you cannot search for events between x and y if x=y. there is nothing between
it. if you are using datetime date type, concat 00:00:00 to your start date
and 23:59:59 to your end date, now you have a valid range that includes the the valid times for the date in question. or for single date searches, do between ? and ? + interval 1 day and pass date twice as '12-25-2015 00:00:00'
also, you are directly using strings in your query, this can open you up to
sql injection attacks. do a google search on bound parameters and never use
a variable in an sql query EVER again.
Try this
$connection->query (
"SELECT meeting_id,visibility,meeting_start
FROM details
WHERE meeting_start BETWEEN '" . $from . "' AND '" . $to . "'"
);

Retrieving today date data from mysql using pdo

I have some data in my table which are [name][address][phone_number] and the date in this format 2015-10-14 14:37:38. I am using php PDO. How can I query out just today date from the table?
The following code is my code to query out result for the past 7 days which worked perfectly. However, whenever I replace it with 1 it doesn't work:
$query = $digital->query('SELECT * FROM sales WHERE `datetime` BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() ORDER BY sale_id DESC');
What I want is to be able to query out all today data inserted into database.
You can use this, haven't tested.
<?php
$todaysDate = date('Y-m-d'); //if your date is stored in y-m-d format
try
{
$s = $conn->query("SELECT * from sales where datetime LIKE '%$todaysDate%'");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$results = $s->fetch(PDO::FETCH_OBJ);
?>
Your query results is now in $results variable.
Extended version
<?php
try
{
$s = $conn->query("SELECT * from sales");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
while($results = $s->fetch(PDO::FETCH_OBJ))
{
$date = explode(" ", $results->datetime);
if($date[0] == date('Y-m-d'))
{
//write code here to display data
}
}
?>
Make sure you replace all the columnNames and tablename.
Edit :-
Here's a sqlfiddle pertaining to my first solution.
http://sqlfiddle.com/#!9/7c2f1/3
I dont know whether it applies to PDO, as I'm not very acquainted to it, but I use to pass the date in a var, then ask for a match in my sql statement
// choose your own timezone here
date_default_timezone_set('America/Sao_Paulo');
// then define your variable as the current time:
$date = date("Y-m-d H:i:s");
then, i'd use the correct PDO syntax to compare the column with the var (a simple "where" statement should do it).
(using codeigniter syntax)
$this->db->where('date', $date);

If statement to check if existing entry is in database

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'];

Categories