Home >Database >Mysql Tutorial >How to convert a string to base64 encoding in MySQL?
In MySQL, the TO_BASE64()
function converts a string to a base-64 encoded string and returns the result. (Related recommendations: "MySQL Tutorial")
Grammar
TO_BASE64(str)
where str is the string that needs to be encoded.
Example 1 - Basic usage
The following is an example to demonstrate basic usage:
SELECT TO_BASE64('Dog');
Result:
+------------------+ | TO_BASE64('Dog') | +------------------+ | RG9n | +------------------+
In this example the parameter is Dog
, once converted to base-64
it becomes RG9n
.
We can use FROM_BASE64()
Function to decode the base-64 string:
SELECT FROM_BASE64('RG9n');
Result:
+---------------------+ | FROM_BASE64('RG9n') | +---------------------+ | Dog | +---------------------+
Example 2 - A longer string
Here is an example using a longer string:
SELECT TO_BASE64('My cat chases dogs!');
Result:
+----------------------------------+ | TO_BASE64('My cat chases dogs!') | +----------------------------------+ | TXkgY2F0IGNoYXNlcyBkb2dzIQ== | +----------------------------------+
Example 3 - Non-string parameter
If the parameter is not a string, it will be converted to a string first:
SELECT TO_BASE64(123);
Result:
+----------------+ | TO_BASE64(123) | +----------------+ | MTIz | +----------------+
Example 4 - NULL parameter
If you enter NULL, you will get NULL:
SELECT TO_BASE64(NULL);
Result:
+-----------------+ | TO_BASE64(NULL) | +-----------------+ | NULL | +-----------------+
Example 5 - Missing Parameter
If you do not pass a parameter, you will get an error:
SELECT TO_BASE64();
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'TO_BASE64'
Example 6 - Too many parameters
If you pass in too many parameters, you will also get an error:
SELECT TO_BASE64('Cat', 'Dog');
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'TO_BASE64'
This article is about the method of converting strings to base64 encoding in MySQL. I hope it will be helpful to friends in need!
The above is the detailed content of How to convert a string to base64 encoding in MySQL?. For more information, please follow other related articles on the PHP Chinese website!