简体   繁体   中英

Converting MYSQL DATE format to STRING format for php

I need help converting a DATE format to STRING format.

I have a variable from a mysql database column which is type DATE.

I want to perform the php explode() function on it, however I get an error saying the parameter must be a string.

This is the code to get the variable from the database:

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

I Then want to use the explode() function on $duedate...

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

I get this error:

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

So I need to convert $duedate to type string. Any help? Thank you.

$duedate is a resource, you need to use mysql_fetch_(something) to access a row of that resource. (There are several functions whose names start with mysql_fetch .)

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

I changed it so that $result is the resource, $row is a row out of that resource, and $duedate is the data you're after.

Use DATE_FORMAT as suggested by @Steve in your code before this.

您在mysql_query之后缺少mysql_fetch_assoc

You can actually do this within the SQL so you don't have to mess around with it in PHP: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

For example, if you wanted your date to be formatted 12 April, 2000, you would do:

SELECT 
  DATE_FORMAT(`duedate`, '%e %M, %Y') as `duedate`
FROM 
 `mtt_todolist`
WHERE 
  `id` = $id;

And remember to make sure $id is escaped so you don't fall victim to SQL Injection!

mysql_query() returns a resource, not the actual results. Read the examples to figure out how to properly use it. It looks like you probably want to do something like this:

$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']);
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM