Page 1 of 1

Left() in PHP

Posted: Sat Nov 12, 2005 12:32 pm
by jwalsh
Hey,

I have a function that returns the timestamp from a database, first 8 characters..

Code: Select all

SELECT LEFT(daytime, 8) FROM log
Now, to get the year (first 4 characters), I'm currently using this code.

Code: Select all

$year = $dates['LEFT(daytime,8)'][0] . $dates['LEFT(daytime,8)'][1] . $dates['LEFT(daytime,8)'][2] . $dates['LEFT(daytime,8)'][3];
Surely there is a more elegant solution, I think using sprintf, but that function confuses the hell out of me :)

Any suggestions?

Josh

Posted: Sat Nov 12, 2005 1:00 pm
by josh
Select the entire timestamp and use date()

Posted: Sat Nov 12, 2005 1:05 pm
by trukfixer
OK so why dont you do

Code: Select all

$sql = "select left(daytime,4) as year,left(daytime(8) from log";
then you have the field 'year' from the selected rows.. no need to do further processing? (let mysql do the dirty work)
Thusly:

Code: Select all

mysql> select left(modified,4) as year, left(modified,8) from cp_domains limit 2;
+------+------------------+
| year | left(modified,8) |
+------+------------------+
| 2005 | 20050624         |
| 2005 | 20050415         |
+------+------------------+

Posted: Sat Nov 12, 2005 1:43 pm
by jwalsh
I like it! Thanks.

Posted: Sun Nov 13, 2005 1:05 pm
by twigletmac
Instead of using LEFT() you can also use YEAR():

http://dev.mysql.com/doc/refman/5.0/en/ ... #id3017176

Mac