2016-03-06 43 views
1

我建立一個博客和IM試圖這樣做,我可以按年份和月份進行排序,但我得到的錯誤:排序的博客文章,轉換失敗

SQLSTATE[22007]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Conversion failed when converting date and/or time from character string.1

顯然我使用微軟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 

我已經嘗試了一些選擇轉換blablabla,但還沒有得到它的工作.. 的日期被存儲在像2016年1月1日HH分貝:MM:SS

回答

2

如果$踵[」 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 
+0

以date_format(新的DateTime($踵[' 5' ])中, 'D MY,H:I');排在後來,即時通訊嘗試訪問該網站通過像mysite.com/index.php?year_month=2016-02,隨着你的線我剛剛得到一個空白空間,一旦我把'在前面和後Ymd H:米: s –

+0

我想我必須做SELECT行的某種轉換,但我不知道,因爲我是一種菜鳥... –

+1

我改進了答案來處理你的輸入像這樣'2016-02' –