簡體   English   中英

如何從MySQL表行中獲取日期和時間

[英]How do i fetch date and time from MySQL table row

我發現PC上出現了一個舊的博客腳本(很舊)。 我在從數據庫中獲取日期和時間以在PHP中顯示時遇到麻煩。 有人能幫我嗎。
這是我的MySQL數據庫設置。

CREATE TABLE blog_posts (
  id int(11) NOT NULL auto_increment,
  title varchar(30) NOT NULL default '',
  news text NOT NULL,
  poster varchar(15) NOT NULL default '',
  date timestamp(14) NOT NULL,
  PRIMARY KEY  (id)
) TYPE=MyISAM;


這就是即時通訊用來發送帖子的內容:

<?php

include "db.php";   
    $title=$_POST['title'];
    $news=$_POST['news'];
    $poster=$_POST['poster'];

    $query="INSERT INTO $blogposts (title, news, poster) VALUES ('$title', '$news', '$poster')";
    $result=mysql_query($query) or die (mysql_error());

    mysql_close();

    header("Location: post.php");
?>


最后,這就是即時通訊在前端調用日期的方式:

<?php echo "posted on: - ".$day.".".$month.".".$year." at ".$hour.":".$min; ?>


我不是專家(顯然),但是約會的電話對我來說似乎不對。 任何人都對我如何使它工作甚至變得更好有任何想法?
編輯::

<?php

    include "db.php";

//query
    $query="SELECT * FROM ".$blogposts." ORDER BY id DESC LIMIT 0,$limit ";
    $result=mysql_query($query) or die (mysql_error());

//loop
    while($row=mysql_fetch_array($result))
    {
$querycomment = "SELECT ID FROM ".$newscomments." WHERE newsid=".$row['id'];
$resultcomment=mysql_query($querycomment) or die (mysql_error());
$num_rows = mysql_num_rows($resultcomment);

    ereg("^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})",$row['date'],$res);
    $year=$res[1];
    $month=$res[2];
    $day=$res[3];
    $hour=$res[4];
    $min=$res[5];
    $sec=$res[6];


?>


謝謝

您似乎沒有在insert命令的date字段中添加任何值。 您可以使用now()添加當前時間戳,以在插入過程中添加當前時間。 要提取時間,您可以(a)從表中讀取日期字段並使用PHP格式化時間,或者(b)使用mysql日期和時間函數在select命令中獲取時間戳的格式化字段。

您還需要一些代碼來讀取PHP中的值以讀取字段的值。 這似乎是您的問題中所缺少的。

由於date列具有TIMESTAMP數據類型,並且沒有null約束,因此如果在插入時date列上沒有發布任何數據,它將具有默認的current_timestamp值。 參見mysql timestamp參考手冊

因此,要獲得一個結果,您要求您可以嘗試使用以下代碼來獲取數據:

$sql = "select id, title, news, poster, DATE_FORMAT(date,'%d.%m.%Y at %k:%i') as posteddate from blog_posts";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
    echo $row["title"]."<br/>";
    echo "By : " . $row["poster"]."<br/>";
    echo "posted on: -  " . $row["posteddate"]."<br/>"; //"posted on: - 03.03.2011 at 7:35"
}

您確定沒有定義要使用的任何日期變量嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM