Left() in PHP

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
jwalsh
Forum Contributor
Posts: 202
Joined: Sat Jan 03, 2004 4:55 pm
Location: Cleveland, OH

Left() in PHP

Post 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
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

Select the entire timestamp and use date()
User avatar
trukfixer
Forum Contributor
Posts: 174
Joined: Fri May 21, 2004 3:14 pm
Location: Miami, Florida, USA

Post 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         |
+------+------------------+
User avatar
jwalsh
Forum Contributor
Posts: 202
Joined: Sat Jan 03, 2004 4:55 pm
Location: Cleveland, OH

Post by jwalsh »

I like it! Thanks.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Instead of using LEFT() you can also use YEAR():

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

Mac
Post Reply