Search code examples
phpmysqlcharstrposalphanumeric

PHP String position handling names with apostrophes


If there is a name in a database (ie. O'Reilly) and I create the insert statement to insert this name into a database via a SQL query in a PHP script, it will cause an error because the apostrophe in the name will end the string and cause the query to fail ('O'Reilly'). Is there a way to use strpos() to find these apostrophes and replace them with a dash/space/comma/etc.

I have tried

$pos = strpos($value, "'"); 

if($pos!==false)
{
  $value[$pos] = "-"; 
}

But this will replace more than what I want in some columns. I was hoping for something more like

$pos = strpos($value, "char'char"); 

if($pos!==false)
{
  $value[$pos] = "-"; 
}

Where the words "char" were replaced with some alphanumeric indicator so that the script knew to only replace the apostrophes in the names. Is there a way to do that in PHP?

This question has nothing to do with SQL injection, I am just trying to handle strings with apostrophes in them.


Solution

  • Try addslashes to escape the slashes.

    $string = addslashes($value);