Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Aug 2002
    Posts
    73
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy str_replace Problem & single quotes...

    I'm trying to take a user-inputted string and insert into a database. So when I'm building the query in PHP, I want to replace a single quote ' with two-single quotes '' (not a double quote) so that SQL can parse the query correctly. Sounds simple, but I keep getting strange results. Here is the code in question:
    Code:
    ...str_replace("''","'",$_POST['Title'])...
    For example, when the $_POST['Title'] variable = Ptty 359 Won't Boot
    The resulting string is:
    Code:
    Ptty 359 Won\''t Boot
    Why is PHP so kind as to add the slash in there? It's causing my SQL query to bomb. Help, I'm pulling my hair out.

  • #2
    Senior Coder Nightfire's Avatar
    Join Date
    Jun 2002
    Posts
    4,266
    Thanks
    6
    Thanked 48 Times in 48 Posts
    You need to use stripslashes()

  • #3
    New Coder
    Join Date
    Aug 2002
    Posts
    73
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thumbs up

    I tested on this data: Ptty 359 Won't Boot http:\\Test.com\Index.php

    On the code
    Code:
    stripslashes(str_replace("''","'",$_POST['usr']))
    And the results were perfect.
    Code:
    Ptty 359 Won''t Boot http:\\Test.com\Index.php
    Thanks!

  • #4
    New Coder
    Join Date
    Aug 2002
    Posts
    73
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Tweak for MySQL/MS-SQL

    The code above works for MS-SQL, I had to make a correction in my abstraction to get it to work with MySQL. MySQL removes \ & changes \\ to \ so I was losing user-entered slashes.
    Code:
    str_replace("\\","\\\\",stripslashes(str_replace("'","''",$teststr)))


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •