2012-02-19 113 views
1

我需要幫助將DATE格式轉換爲STRING格式。將MYSQL DATE格式轉換爲STRING格式,用於php

我有一個類型爲DATE的mysql數據庫列的變量。

我想執行php explode()函數,但是我得到一個錯誤,說參數必須是一個字符串。

這是代碼從數據庫中獲取變量:

$duedate = mysql_query("SELECT duedate FROM mtt_todolist WHERE id=$id") ; 

我於是想使用$交貨期的爆炸()函數...

$date = explode("-", $duedate); 

我得到這個錯誤:

Warning: explode() expects parameter 2 to be string, 

所以我需要將$ duedate轉換爲字符串類型。任何幫助?謝謝。

+0

做'var_dump($ duedate)'。我敢打賭這也不是一個約會。這可能是結果集或「資源」。在這種情況下,'$ duedate-> duedate'可能會起作用。 – 2012-02-19 17:01:37

+1

您忘記從資源鏈接中獲取行,使用'mysql_fetch_row'或類似的。 – 2012-02-19 17:01:59

+0

有關如何查詢數據庫的示例,請參見[manual](http://php.net/mysql_query)。 – 2012-02-19 17:03:05

回答

1

$duedate是一種資源,您需要使用mysql_fetch_(something)來訪問該資源的一行。 (有幾個函數的名字開始mysql_fetch

$result=mysql_query(...); 
$row=mysql_fetch_assoc($result); 
$duedate=$row['duedate']; 

我改變它,以便$結果是資源,$行是行的是資源,而$duedate是你後的數據。

使用DATE_FORMAT在此之前您的代碼中由@Steve建議。

+0

謝謝,這工作。 – user1197558 2012-02-19 17:21:50

0

mysql_query()返回資源,而不是實際結果。閱讀示例以瞭解如何正確使用它。看起來你可能想這樣做:

$query = sprintf('SELECT duedate FROM mtt_todolist WHERE id = %s', 
      mysql_real_escape_string($id) 
     ); 
$result = mysql_query($query); 
if (!$result) { 
    $message = 'Invalid query: ' . mysql_error() . "\n"; 
    $message .= 'Whole query: ' . $query; 
    die($message); 
} 

// Use result 
// Attempting to print $result won't allow access to information in the resource 
// One of the mysql result functions must be used 
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc. 
while ($row = mysql_fetch_assoc($result)) { 
    $date = explode('-', $row['duedate']); 
    ... 
}