-1

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.

  • 1
    use `escape string` or `addslashes()` before storing – Kamran Apr 13 '15 at 19:21
  • @KamranAdil: -infinite. `addslashes()` is about as useful for sql injection prevention as a piece of wet toilet paper is in drying out an ocean. e.g. UTTERLY USELESS. – Marc B Apr 13 '15 at 19:26
  • 1
    @MarcB I agree with you but question was about apostrophes and I mentioned `escape string` before `addsalshes`. – Kamran Apr 13 '15 at 19:36
  • This question has nothing to do with SQL injection. I'm just trying to handle last names in a database that have an apostrophe. – Skyfactor_interns Apr 13 '15 at 21:43
  • It's possible the ANSWER to the question is the same as the one about SQL injection. But the QUESTION is not a duplicate. Voting to reopen. – O. Jones Apr 14 '15 at 01:07

2 Answers2

0

If you want to replace something in the string, just use str_replace()

$str = str_replace($str, "'", '-');
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
0

Try addslashes to escape the slashes.

$string = addslashes($value);
Muhammad Abdul-Rahim
  • 1,980
  • 19
  • 31
  • addslashes is utterly USELESS to prevent sql injection, and would only be even mildly useful for any database which uses backslashes as escape characters. – Marc B Apr 13 '15 at 19:27
  • 2
    This question isn't about SQL injection, it's about handling strings with apostrophes in them. There's a time and place for every discussion: stay within the scope of the question. – Muhammad Abdul-Rahim Apr 13 '15 at 19:29