On the need of encoding
With many encryption methods, the ciphertext, i.e. the encrypted form of a message is an array of bytes, i.e. if viewed as sequence of "characters" the ciphertext could include any character between 0 and 255 (decimal) or $00 and $FF (hexadecimal). Such a range of characters includes many non-printable characters, say "tab" or "eot", as well as characters with a code above 128, which interpretation may vary.
Furthermore, even discounting these non-printable or "non-ASCII" characters, some characters in the ciphertext may be such that they "throw off" the interpretation of a possible format where the ciphertext is included (as for example XML, as hinted in the question).
For this reason, ciphertext must often be encoded so that it can be printed or included in text-oriented containers.
All encoding (of binary to text-like format) result in using more space for the encoded form of the data. Base64 is a popular format because it is relatively compact.
Another possible encoding format is hexadecimal ("base 16") which takes twice the size as the original binary data. Hexadecimal is also simpler/easier to use since there is a direct mapping between any byte in the input and its two corresponding characters in the output. (whereby Base64 uses 1.25 characters to encode one byte, leading to blocks of 3 input bytes for encoded bytes)
On the need to "Escape" encoded data
Once the cyphertext is encoded, it may still include characters susceptible of throwing-off the structure of the "outside" format where the ciphertext is included, and that is why, in the case of XML, you may want to "escape" this content as CDATA. (This is not necessary with Hexadecimal, and may not be needed in Base64, depending on the two extra character used (Base64 uses 0 thru 9, A thru Z, a thru z and two extra characters, typically + and /, as well as =).
On the need of storing data in database as Base64 (or other encoding)
People use Base64 (or similar encodings) to store data in databases for two distinct reasons:
- to introduce a [mild/weak] encryption, for data which is readily in text form. It is a weak form of encryption, as someone may quickly identify the encoding. Never the less it makes the data stored less "obvious".
- to store data that is in binary form, as TEXT.
Most DBMSes include data types that allow stroring sequences of bytes in binary format, and it would therefore not be necessary to use encoding and storage to a Text-type format. However, there are many reasons why people may still choose to store as text:
- because the data is eventually handed-out/used as encoded text (no need encrypt at run time, just encrypt once when data is stored)
- to facilitate portability
- to make debugging easier