20

Basically - its a long story - but I have a field in a database that is encoded as a base64 string.

EG: this is stored in the database:

YToyOntzOjIwOiJUeXBlX29mX29yZ2FuaXNhdGlvbiI7czoyMDoiTWVtYmVyIG9mIFBhcmxpYW1lbnQiO3M6ODoiUG9zdGNvZGUiO3M6NzoiUEUxIDFKQSI7fQ==

Which equals this:

a:2:{s:20:"Type_of_organisation";s:20:"Member of Parliament";s:8:"Postcode";s:7:"#postcode#";}

What I want to be able to do is select where this string LIKE '%Member of Parliament%'. Is there any way to base64 decode a mysql column before performing a WHERE?

eg: SELECT * FROM table WHERE base64_decode(column) LIKE '%Member of Parliament%'

Thanks

5
  • 1
    possible duplicate of base64 encode in MySQL
    – Chandu
    Jun 28, 2011 at 13:44
  • What version of MYSQL are you using ? Maybe you can write a UDF for this?
    – jahsen
    Jun 28, 2011 at 13:48
  • 1
    possibly... lack of an answer though. Plus I'm looking to decode, not encode. Jun 28, 2011 at 14:03
  • Mysql 5.0.5 - what's a UDF? I've found a stored procedure online, but apparently it's extremely inefficient. Jun 28, 2011 at 14:04
  • User defined function Jan 28, 2014 at 15:34

1 Answer 1

39

If you're using MySQL 5.6.1 or higher you can use the FROM_BASE64() function:

Takes a string encoded with the base-64 encoded rules used by TO_BASE64() and returns the decoded result as a binary string. The result is NULL if the argument is NULL or not a valid base-64 string. See the description of TO_BASE64() for details about the encoding and decoding rules.

This function was added in MySQL 5.6.1.

mysql> SELECT TO_BASE64('abc'), FROM_BASE64(TO_BASE64('abc')); -> 'JWJj', 'abc'

Otherwise you can use the User Defined Function from: https://github.com/y-ken/mysql-udf-base64

4
  • Is there an equivalent function in MySQL 5.1?
    – Randell
    Mar 21, 2014 at 4:36
  • Not that I know, you'll have to define your own function with the base64.sql Mar 24, 2014 at 20:02
  • Link is broken to wi-fizzle
    – n0nag0n
    Mar 11, 2016 at 19:39
  • Thanks @ImmortalFirefly, found another link. Let me know if this works for you. Mar 15, 2016 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.