按日期排序博客帖子,转换失败

时间:2016-03-06 22:47:28

标签: php sql-server datetime pdo

我正在建立一个博客,我试图这样做,我可以按年和月排序,但我得到错误:

  

SQLSTATE [22007]:[Microsoft] [SQL Server Native Client 11.0] [SQL   服务器]转换日期和/或时间时转换失败   character string.1

显然我正在使用Microsoft SQL服务器来说清楚。

我已按照这样的方式显示帖子

  

date_format(new DateTime($ postdate ['5']),'d M Y,H:i');

那么我如何在这件作品上实现这样的东西呢?

if (isset($_GET['year_month']))
{
    $bdate = $_GET['year_month'];               
    $tsql4 = "SELECT * FROM blog_posts WHERE blog_date=:bdate ORDER BY blogID DESC"; 
    $stmt5 = $conn->prepare($tsql4);
    $stmt5->execute (array($bdate));
    while($postdate = $stmt5->fetch(PDO::FETCH_BOTH) )
    { 
     here i post the $postdate rows 

我尝试了一些SELECT转换blablabla但还没有让它工作.. 日期存储在数据库中,如2016-01-01 HH:MM:SS

1 个答案:

答案 0 :(得分:2)

如果$ postdate [' 5']等于$ _GET [' year_month'],那么您可以使用此代码:

if (isset($_GET['year_month']))
{
    // $_GET['year_month'] looks like '2016-02';
    list($year, $month) = @explode('-', $_GET['year_month']);
    $day = 1;
    $datetime = new DateTime();
    $datetime->setDate($year, $month , $day);
    $datetime->setTime(0, 0, 0);
    $bdate_start = date_format($datetime, 'Y-m-d H:m:s');
    $datetime->add(new DateInterval('P1M'));
    $bdate_finish = date_format($datetime, 'Y-m-d H:m:s');

    $tsql4 = "SELECT * FROM blog_posts WHERE blog_date BETWEEN :bdate_start AND :bdate_finish ORDER BY blogID DESC"; 
    $stmt5 = $conn->prepare($tsql4);
    $stmt5->execute (array($bdate_start, $bdate_finish));
    while($postdate = $stmt5->fetch(PDO::FETCH_BOTH) )
    { 
     here i post the $postdate rows