Easiest Way to Save Any Code into Database

by Hiroshi on April 4, 2013

in database

I was working with the admin of a website and client needed to save Google Analytic code into the database. So I created a panel where he could save JavaScript code into database table to retrieve it in footer of website on every page. And then I created a section to save meta code for head section of website in database. That worked fine but it was not saving JavaScript code into the database. HTML code can be saved in database easily without any error. If you want to save JavaScript or PHP code into database, then you need a work around for that.

You have to use mysql_real_escape_string to escape all characters that could break the query. mysql_real_escape_string() calls MySQL’s library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ‘, ” and \x1a.

You can also achieve this by using prepared statements.

This is a security feature in PHP that does not allow code with special characters to be saved into database. It is to prevent SQL injection or cross site scripting attacks (XSS attacks).

But in such case when you need to provide a way to save code in database, the easiest solution is to encode before saving and then decode it after retrieving from database, before displaying it.

Get the code > encode it > save in DB.
Get the encoded data > decode it > print it.

I am talking about the base64_encode and base64_decode.

How to Encode and Decode Data in PHP

<?php
$str = 'This is an encoded string';
echo base64_encode($str);
?>

The above example will output: VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>

The above example will output: This is an encoded string

By using above method you can store PHP code or JavaScript code into database table easily.

Related Posts

Previous post:

Next post: