2012-09-26 47 views
0

我有这个代码,它允许我检索所有信息的时间戳有关该信息等于另一个日期。比较时间戳和日期在php

下面是代码:

$information="SELECT * FROM scheda_anagrafica WHERE FROM_UNIXTIME('time_inserted','%d-%m-%Y') = '" . $giorno_selcted. "' 
"; 
$result1 = mysql_query($information) or die (mysql_error()); 
while($row = mysql_fetch_array($result1)) { 

    echo $row['information1']; 

} 

giorno_selected印像:25-09-2012 什么我错在这里做什么? 谢谢!

+0

你好,请你解释一下多一点? – nana

+0

$ giorno_selcted – RomanKonz

+0

的内容是肯定的,所以我在数据库中有一个字段,它是一个timstamp,当前日期即;让我们假设时间戳给我23-09-2012 12:23:45和日期变量给我23-09-2012,我需要检查时间戳和日期是否相等,但我需要在查询中这样做。 – Tao

回答

0

首先,你不应该在where子句中的操作符左侧使用mysql函数。这样mysql需要读取磁盘上的完整表来计算要比较的值,而不是优化查询速度和资源使用情况(IO,cpu)。

从你的问题和意见我明白,你正在查询数据库的行与$giorno_selected代表的字符串有同一天。所以你需要找到特定日0:00到23:59之间,时间戳的所有行:

$giorno_timestamp_start = date_create_from_format('d-m-Y', $giorno_selected)->getTimestamp(); 
$giorno_timestamp_end = $giorno_timestamp_start + 86399; //add almost all seconds per day onto the start timestamp 

$information="SELECT * FROM scheda_anagrafica WHERE time_inserted BETWEEN " . $giorno_timestamp_start. " AND ". $giorno_timestamp_end; 
$result1 = mysql_query($information) or die (mysql_error()); 
while($row = mysql_fetch_array($result1)) { 

    echo $row['information1']; 

} 

这个作品,如果你time_insertedinteger型和持有unix_timestampds。 如果是datetime型或timestamp您需要修改本查询:

$information="SELECT * FROM scheda_anagrafica WHERE time_inserted BETWEEN FROM_UNIXTIME(" . $giorno_timestamp_start. ") AND FROM_UNIXTIME(". $giorno_timestamp_end .")"; 
+0

嘿,谢谢,以及我不明白这一点,你能告诉我,我怎样才能将时间戳转换成使用d-m-Y的日期函数?所以我可以立即在查询中比较它们? 我使用日期函数做了它,但它给了我一个奇怪的日期,比如1970-01-01 – Tao

+0

为了比较你需要的东西,确保它是相同类型的。否则,你会比较苹果与橙子。因此,为了比较一个像'23-09-2012'这样的字符串与数据库中的整数像'1348674213',您需要将该字符串转换为一个表示相同值的整数。这就是'date_create_from_format()'函数所做的。 –

+0

是的,但问题是,我需要从查询进行比较,我的意思是我需要使用类似这样的东西:WHERE date('dm -Y',strtotime('time_inserted')='26- 09-2012'where time_inserted is the field ... – Tao