I have this query:
$sql = " INSERT INTO table SET name = '$name', sku = '$number', description = '$desc' ";
But the rows containing some special characters (in my case this ') are not inserted.. How I can solve? Thanks in advance.
I have this query:
$sql = " INSERT INTO table SET name = '$name', sku = '$number', description = '$desc' ";
But the rows containing some special characters (in my case this ') are not inserted.. How I can solve? Thanks in advance.
You must use parameterised queries instead of manually appending those values. Currently if name, number or description would contain any sql it would get executed.
A lot more detailed answer is in How can I prevent SQL injection in PHP?
When you construct your query, you need to escape the data you are inserting. You need to at least use addslashes() function in PHP, like this:
$sql = "INSERT INTO table SET name = '".addslashes($name)."', sku = '".addslashes($number)."', description = '".addslashes($desc)."'";
However more correct way is to use a different function than addslashes, which would properly handle all characters in the data, not only apostrophes.
I am using my custom 'escape' function like this:
function escape($text)
{
return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $text);
}
So using this function, you would write:
$sql = "INSERT INTO table SET name = '".escape($name)."', sku = '".escape($number)."', description = '".escape($desc)."'";