Query to get the length of string in mysql

In this programming tutorial you will learn how to get the length of string in mysql. I have already written the same tutorial for ms sql server. It is quite easy in mysql too. Let’s have a look over it.
Query to get the length of string in mysql
select length("Arman Malik") as length
Output:-
11

You can also use single quote within length() function like given below
select length('Arman Malik') as length

Output:-
11

Using single quote within the length() function can cause the sql injection if user will enter the ' and \ with the string like given below

select length('Arman's Malik')

It will throw the following error

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Fakhar') as length' at line 1.

So if you want to prevent the sql injection then use double quotes within the length function but if you want to use the single quote within the length() function and also want to prevent the sql injection then use \ like given below

select length('Arman\'s Malik') as length

Output:-
13

So that's it. I hope you will found this tutorial very handy and informative.

I love your feedback.

0 comments: