PHP - Using only the first x characters of a database entry.

Soldato
Joined
26 Aug 2006
Posts
9,726
Location
62.156684,-49.781113
Long day at work, now my Google is failing me for what was meant to be a quick alteration. I want a preview of the first x characters of a larger block of text stored in mysql database. I've retrieved the string, now how can I cut the first so many characters out into a new variable? :)

Apologies if this is really simple, I'm picking up PHP as I go along because there's a delay on my book order, I got bored of waiting...
 
google 'mysql string functions', first hit, scroll down till you see 'LEFT(str,len)'. I reckon that's the function that would be useful to you :)

you'd probably do something like - select left(text_field, 50) from text_table - where 50 is the number of characters you want.
 
Last edited:
Yeah, I went back to thinking properly. Here's a more complicated one then, how can I stop it from cutting off in the middle of a word? :p
 
gumbald said:
Yeah, I went back to thinking properly. Here's a more complicated one then, how can I stop it from cutting off in the middle of a word? :p


Check out the string functions of MYSQL - http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

In terms of deciding whether to do the LEFT() in MYSQL or in PHP, best practice is to fetch only the required data from the database. So by default I would go with doing this in MYSQL. Obviously if you know for definite that you'll later need to fetch the full string anyways, then you might consider fetching the whole string, and doing the LEFT() in PHP.
 
Back
Top Bottom