Hello. Can anyone tell me how to insert special characters into a MySQL database? I've made a PHP script which is meant to insert some words into a database, although if the word contains a ' then it wont be inserted.
I can insert the special characters fine when using PHPmyAdmin, but it just doesn't work when inserting them via PHP. Could it be that PHP is changing the special characters into something else? If so, is there a way to make them insert properly? Thanks!
views:
507answers:
7Are you escaping? Try the mysql_real_escape_string() function and it will handle the special characters.
$insert_data = mysql_real_escape_string($input_data);
Assuming that you have the data stored as $input_data
You are most likely escaping the SQL string, similar to:
SELECT * FROM `table` WHERE `column` = 'Here's a syntax error!'
You need to escape quotes, like follows:
SELECT * FROM `table` WHERE `column` = 'Here\'s a syntax error!'
mysql_real_escape_string()
handles this for you.
use mysql_real_escape_string
So what does mysql_real_escape_string do?
This PHP library function prepends backslashes to the following characters: \n, \r, \, \x00, \x1a, ‘ and “. The important part is that the single and double quotes are escaped, because these are the characters most likely to open up vulnerabilities.
Please inform yourself about sql_injection. You can use this link as a start
You are propably pasting them directly into a query. Istead you should "escape" them, using appriopriate function - mysql_real_escape_string, mysqli_real_escape_string or PDO::quote depending on extension you are using.
Note that as others have pointed out mysql_real_escape_string() will solve the problem (as will addslashes), however you should always use mysql_real_escape_string() for security reasons - consider:
SELECT * FROM valid_users WHERE username='$user' AND password='$password'
What if the browser sends
user="admin' OR (user=''"
password="') AND ''='"
The query becomes:
SELECT * FROM valid_users
WHERE username='admin' OR (user='' AND password='') AND ''=''
i.e. the security checks are completely bypassed.
C.