1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Limit number of characters to display from a MySQL query

Discussion in 'PHP' started by carl_in_florida, Aug 6, 2007.

  1. #1
    I am barely a hack when it comes to PHP so please forgive my terminology:

    I am getting a row from a MySql Database and displaying several fields. One of the fields is text and I would like to display only the first 50 characters in the field.

    How in the world can I do this?

    I am currently using this:

    But it displays the whole text. I just want the first 50 characters or so.

    Thanks for the help.
     
    carl_in_florida, Aug 6, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    nico_swd, Aug 6, 2007 IP
    carl_in_florida likes this.
  3. carl_in_florida

    carl_in_florida Active Member

    Messages:
    1,066
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    90
    #3
    WOW! Thanks. I would have never found that.
     
    carl_in_florida, Aug 6, 2007 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    Personally I would do it on a sql level as long as you dont need all the data at any time in the script. It reduces a little of the processing time (usually) and also eliminates the extra data from hitting php at all.

    
    
    $query = "SELECT SUBSTR(title,0,50), other columns... FROM database ....";
    
    
    PHP:
     
    jestep, Aug 6, 2007 IP
    carl_in_florida likes this.
  5. gwkg

    gwkg Peon

    Messages:
    143
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #5
    You can use LEFT instead of SUBSTR

    $query = "SELECT LEFT(text,50) FROM table";

    You can also add a string to the end to signify that you cut off the text and there is actually more. Something like '...'

    This is what I am selecting from my table. I only...

    $query = "SELECT CONCAT(LEFT(text,50),'...') FROM table";

    Heres a whole list of MySQL 5.0 string functions (LEFT & CONCAT work in 4.1):

    hxxp://dev.mysql.com/doc/refman/5.0/en/string-functions.html

    hxxp://dev.mysql.com/doc/refman/4.1/en/string-functions.html
     
    gwkg, Aug 6, 2007 IP
    carl_in_florida likes this.
  6. carl_in_florida

    carl_in_florida Active Member

    Messages:
    1,066
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    90
    #6
    I am guessing that both of these ease resources?

    btw ... green for everyone!
     
    carl_in_florida, Aug 6, 2007 IP