0

I am using mysql with PHP. I have a problem with inserting the apostrophe value in database. However I use -

$newstring = str_replace("'","'",$string);

OR

$newstring = str_replace("'","''",$string);

but how could I fetch the string as it is?

Thanks.

hakre
  • 184,866
  • 48
  • 414
  • 792
SandyK
  • 413
  • 8
  • 25
  • 1
    I'm confused by your question. Could you clarify 'fetch the string as is'? – switz Jul 18 '11 at 13:00
  • Possible Duplicates: [How do you encode an apostrophe so that it's searchable in mysql?](http://stackoverflow.com/questions/620783/how-do-you-encode-an-apostrophe-so-that-its-searchable-in-mysql); [PHP Apostrophe and query string.](http://stackoverflow.com/questions/2951250/php-apostrophe-and-query-string) – hakre Jul 18 '11 at 13:00
  • @user820561: Next to the problem you have to actually store the string (I assume you want to store it unchanged) to the database, you're probably even facing a SQL injection. You can store the string unchanged into the database by making use of the `mysql_real_escape_string` function instead of using your self-cooked `str_replace`. That's for what it has been made for. And it helps to prevent sql injections. – hakre Jul 18 '11 at 13:09

2 Answers2

4

Use mysql_real_escape_string:

mysql_real_escape_string($string)
Sarfraz
  • 367,681
  • 72
  • 526
  • 573
  • thanks for your suggesation. I used it, but while inserting it into table it inserts value as - abcd\'s , so while fetching string comes as it is abcd\'s. How can I avoid this? – SandyK Jul 18 '11 at 13:24
  • @user: While fetching, use `stripslashes` function :) – Sarfraz Jul 18 '11 at 15:45
2

you need to escape it, use addslashes() to sanitise it, or better yet, mysql_real_escape_string()

Olipro
  • 3,429
  • 18
  • 24