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.
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.
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