When adding JavaScript code to a MySQL database, it is important to use mysql-real-escape-string. This function helps prevent SQL injection attacks by escaping special characters in the code string. Here's an example of how to properly insert JavaScript code into a database:
HTML:
<form action="save_code.php" method="POST">
<table>
<tr>
<td>Code</td>
<td><textarea name="code"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Save" value="Save"/></td>
</tr>
</table>
</form>
PHP: save_code.php
// Comment out this for real test
//$jsCode = $_POST['code'];
//Assign js code string to variable
$jsCode = '<script type="text/javascript">
var count = 0;
function countClicks() {
count = count +1 ;
document.getElementById("likes").innerHTML = count;
}
</script>
<input type="button" value="Like "onclick="javascript:countClicks();" alt="alt text"/>
<div id="likes">0</div>';
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die(mysql_error());
$query = "INSERT INTO your_table(id, code) VALUES('', mysql_real_escape_string($jsCode))";
mysql_query($query);