PHP/MySQL Limiting characters outputted from a field

When I get a database array, sometimes there is fields with too much data for my results list page, which is suppose to give just a short description. How do I limit the characters count to something like 100.

This is my array for the loop:

<?php
    $i = 1;
    while ($row = mysql_fetch_array($result)) {
?>

This is my echo statement:

<?php echo $row['description']; ?>

Answer

You can use substr like this:

<?php echo substr($row['description'], 0, 100); ?>

But it might be better—depending on your application needs—to do the limiting when making the initial MySQL query using SUBSTR which behaves the same way, but in MySQL.

SELECT SUBSTR(example_field, 1, 100)
FROM example_table
WHERE example_field IS NOT NULL
LIMIT 1
;

That MySQL script basically means return the substring of example_field starting from the first (1) character and going 100 characters in.

This might be better in some cases since if you are limiting text length to 100 characters, why grab the data for fields that might have 1,000+ characters? That would definitely bog down your PHP script in many cases. Handling that in MySQL is the best way to nip it in the bud if your app just needs 100 characters returned.