开发者

a little more help in this simple script about date() function in PHP

why wont this work? this is in a while loop:

$postdate = date( "j F", strto开发者_如何学运维time( $row['insert_date'] ) );
if ($postdate == date("j F")) {$postdate = "today"};
 $table .= bla bla bla "$postdate";

it gives an error on the 'if statement line' in my browser...

$postdate is something like 14 october before the if statement!

Thanks


The semicolon needs to be inside the braces, like this:

if ($postdate == date("j F")) {$postdate = "today";}


your $table .= bla bla bla "$postdate"; line is wrong, it should read:

$table .= 'bla bla bla' . $postdate;


Your third line is formatted wrong. Try this:

$table .= "bla bla bla $postdate";


You can let the MySQL server do the comparison (if you like)

SELECT
  x,y,z,insert_date, Date(insert_date)=Curdate() as today
FROM
  foo
WHERE
  somecondition....

The field today will contain 1 if the date equals "today" or 0 otherwise.
edit: you're "only" comparing the day/month part of the timestamp. You can extract these parts with the Day()/Month() functions, though imo the solution loses some of its "elegance" that way. And I would consider something like

SELECT ... (Date(insert_date)-Curdate()) mod 10000 as today ...

an ugly hack :(

e.g.

$pdo = new PDO('mysql:host=...;dbname=...', '...', '...'); 
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

// example table 
$pdo->exec('CREATE TEMPORARY TABLE foo (id int auto_increment, insert_date TIMESTAMP, primary key(id))');
// insert three rows, only the second is "for today"
$pdo->exec('INSERT INTO foo (insert_date) VALUES (Now()-Interval - 2 day), (Now()), (Now()-Interval + 1 day)');

foreach( $pdo->query('SELECT id, insert_date, Date(insert_date)=Curdate() as today FROM foo') as $row ) {
  echo
    $row['today'] ? '+' : '-',
    $row['id'], ' ', $row['insert_date'], "\n";
}

prints (right now on my machine)

-1 2009-10-21 17:03:55
+2 2009-10-19 17:03:55
-3 2009-10-18 17:03:55
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜