Limit number of characters in Mysql PHP. add a ... if the length is longer.

Dear Experts.

How do I limit the number of character in the mysql query, but add a ... if the text is longer than say 20 characters. If it is shorter than 20 character then the ... at the end would not show.

This is what I have so far, it limit the number of character but I do not know how to add the ... at the end.

SELECT LEFT(Help.Name, 20) FROM Help WHERE Help.HelpID = 1

If this is not possible in the mysql query would it be possible in the php echo statement.

e.g the result I am looking if the result of the Help.Name was

to be or not to be that is the question

then the result I am looking for it

to be or not to be t...

but if the query result was less than 20 character a ... would not be added to the end.

Many thanks for your help

Who is Participating?
"theGhost_k8" got it right, but a little better variant, imho:

SELECT IF(LENGTH(Help.Name)>20,INSERT(Help.Name,21,-1,'...'),Help.Name) AS Name FROM Help WHERE Help.HelpID = 1;

Open in new window

theGhost_k8Database ConsultantCommented:
you can use combination of if, length & concat
theGhost_k8Database ConsultantCommented:
Oops.. Use this:
Select IF(LENGTH(Help.Name)>20,CONCAT(LEFT(Help.Name,20),'..') FROM Help WHERE Help.HelpID = 1
LightwalkerAuthor Commented:
Hi theGhost k8,

Thanks, for some reason your example is giving me a syntax error, but I can not find it.
theGhost_k8Database ConsultantCommented:
Select IF(LENGTH(Help.Name)>20,CONCAT(LEFT(Help.Name,20),'..'),Help.Name) FROM Help WHERE Help.HelpID = 1;

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.