php
  • mysql
  • date
  • 2012-07-25 56 views 0 likes 
    0

    我在NOW()的數據庫中插入日期,然後查詢結果。這是代碼。從現在開始只查詢一個月的月份()

    function get_content($id = ''){ 
    
    if($id != ''): 
        $id = mysql_real_escape_string($id); 
        $sql = "SELECT * FROM cms_content WHERE id = '$id'"; 
    
        $return = '<p><a href="index.php">Back to Content</a></p>'; 
    else: 
        $sql = "SELECT * FROM cms_content ORDER BY id DESC"; 
    endif; 
    
        $res = mysql_query($sql) or die(mysql_error()); 
    
        if(mysql_num_rows($res) != 0): 
         while($row = mysql_fetch_assoc($res)) { 
          echo '<h1><a href="index.php?id=' . $row['id'] . ' "> ' . $row['title'] . '</a></h1>'; 
          echo '<p>' . stripslashes($row['body']) . '</p>'; 
          **echo '<p>' . $row['date_posted'] . '</p>';** 
          } 
        else: 
         echo '<p> You broke it!, this post dosn\'t exsist!'; 
        endif; 
    
        echo $return; 
    

    echo '<p>' . $row['date_posted'] . '</p>'; 
    

    是我回聲的日期。當我從數據庫回顯這個數據時,我得到了2012-07-25 19:00:46,因爲這就是數據庫中的內容。我的問題是,我如何迴應這一天,然後迴應本月,然後回顧這一年。理想情況下,這些都是獨立的回聲,所以我可以分別進行設計。

    回答

    1

    由於格式是已知的,你可以簡單地使用:

    list($year,$month,$day) = explode("-",substr($row['date_posted'],0,10)); 
    

    然後你就可以呼應不過你想要的那些變量。

    +0

    謝謝!這工作完美! – lilfinn 2012-07-26 01:48:20

    0
    $date = strtotime($row['date_posted']; 
    echo date('d', $date); 
    echo date('m', $date); 
    echo date('Y', $date); 
    

    $date = new DateTime($row['date_posted']); 
    echo $date->format('Y'); 
    

    +0

    爲什麼你會不出來寫上日期都在同一行/函數調用。 – 2012-07-25 23:18:36

    +0

    strtotime並不總是做你期望的。將日期轉換爲人類可讀格式,然後將其轉換回tme,然後再將其轉換爲不同的人類可讀格式,這有點愚蠢。在查詢中使用UNIX_TIMESTAMP()轉換日期將會減少錯誤 - 但仍然是相同的轉換。 – symcbean 2012-07-25 23:20:03

    +0

    ,因爲他說:「理想情況下,這些都將是獨立的回聲,所以我可以每個不同的風格。」 – Kris 2012-07-25 23:23:00

    0

    你可以使用php內置date()功能:http://us.php.net/manual/en/function.date.php

    echo "<p>".date('j M, Y', $row['date_posted'])."</p>"; 
    // would output <p>25 July, 2012</p> 
    

    這可以被修改成只是你想的任何格式。

    0

    另一個選項是做直接在SQL中使用* DATE_FORMAT *功能:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

    2

    這是很多更方便和更少的代碼。

    $date = new DateTime($row['date_posted']); 
    $day = date->format('d'); 
    $month = date->format('F'); 
    $year = date->format('Y'); 
    

    資源:http://www.php.net/manual/en/class.datetime.php

    相關問題