In MySQL, the TO_BASE64() function converts a string to a base-64 encoded string and returns the result.
Syntax
The syntax goes like this:
TO_BASE64(str)
Where str is the string that you want encoded.
Example 1 – Basic Usage
Here’s an example to demonstrate the basic usage:
SELECT TO_BASE64('Dog');
Result:
+------------------+
| TO_BASE64('Dog') |
+------------------+
| RG9n |
+------------------+
So in this example, our argument is Dog, which becomes RG9n once converted to base-64.
We can use the FROM_BASE64() function to decode the base-64 string:
SELECT FROM_BASE64('RG9n');
Result:
+---------------------+
| FROM_BASE64('RG9n') |
+---------------------+
| Dog |
+---------------------+
Example 2 – A Longer String
Here’s 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 Arguments
If the argument is not a string, it will be converted to a string first:
SELECT TO_BASE64(123);
Result:
+----------------+ | TO_BASE64(123) | +----------------+ | MTIz | +----------------+
Example 4 – NULL Argument
You’ll get NULL if you pass in NULL:
SELECT TO_BASE64(NULL);
Result:
+-----------------+ | TO_BASE64(NULL) | +-----------------+ | NULL | +-----------------+
Example 5 – Missing Argument
You’ll get an error if you don’t pass in an argument:
SELECT TO_BASE64();
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'TO_BASE64'
Example 6 – Too Many Arguments
You’ll also get an error if you pass in too many arguments:
SELECT TO_BASE64('Cat', 'Dog');
Result:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'TO_BASE64'