How To Reduce Number Of MySQL Select Character


Here is a tutorial explaining how to limit or reduce the number of character gotten when a MySQL database (and table) is queried.

Below is a practical example on how to achieve this via PHP.

  • Firstly, query the database;
    <?php $sql = $mysqli->query("SELECT * FROM test LIMIT 1");?>
  • Next, we are going to fetch the result and reduce the number of character to “10” using the substr PHP function.
     
    <?php while ($row = $sql->fetch_object())  :
    echo substr($row->name, 0, 10); ?> 
    

    In the above code, are outputting the first 10 characters. you can change the “0” in the above code to the number of character length you want to output.

    To add a triple dot “…” signifying some character has been stripped, the code can be modified to;

     
    <?php while ($row = $sql->fetch_object()) :
    $num = 10;
    echo substr($row->name, 0, $num); 
    if($num >= 10): echo"...";
    endif;
    endwhile; ?>
    

About Agbonghama Collins

Agbonghama Collins is a webdeveloper and an internet geek. I love writing and sharing the little idea & information i know. Hope you enjoyed my Article.

Follow me on Twitter, add him on Facebook or on Google+