简体   繁体   中英

PHP, MySQL; GROUP BY doesn't work for datetime

I have some datetime 's in my MySQL database like this:

2016-11-15 10:00:00
2016-11-16 10:00:00
2016-11-17 10:00:00
2016-11-17 12:00:00
2016-11-17 19:30:00
2016-11-20 10:00:00
2016-12-15 10:00:00
2017-11-15 10:22:00

I want to output, but only once per day. That means:

2016-11-15 10:00:00
2016-11-16 10:00:00
2016-11-17 10:00:00
2016-11-20 10:00:00
2016-12-15 10:00:00

This is my code:

<?php
$stmt = $pdo->prepare('SELECT date_db FROM my_table GROUP BY DATE(date_db) ORDER BY date_db');
$stmt->execute();

$results = $stmt->fetchAll();
foreach( $results as $row ) {

    echo "<option value=\"".$row['date_db']."\">".$row['date_db']."</option>";
}
?>

But this doesn't really work. Some days simply are missing. Why that? What am I doing wrong?

试试这个查询:

SELECT MIN(date_db) FROM my_table GROUP BY DATE(date_db) ORDER BY DATE(date_db)

This is the working code now:

<?php
$stmt = $pdo->prepare('SELECT date_db FROM my_table GROUP BY DATE(date_db) ORDER BY date_db');
$stmt->execute(array(':date' => $date));

$results = $stmt->fetchAll();
foreach( $results as $row ) {

echo "<option value=\"".$row['date_db']."\">".$row['date_db']."</option>";
}
?>

I don't know why it's working now, but it is.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM