Need help using php/mysql to update Text field containing apostrophes

Discussion in 'PHP' started by Darden12, Mar 28, 2009.

  1. #1
    I have been using a PHP script with textarea input from an html form to update a field called Article on my website. This has worked fine for a year. Tonight I have been trying to make a new version of this form, and I've apparently done something wrong, because the field will no longer update if it contains an apostrophe (and the lengthy Article field always does contain many apostrophes).

    I have tried using htmlentities, and it still doesn't work. Perhaps I'm using that function in the wrong place in my code. Any ideas would be appreciated on how to solve this. Below is an outline of how my current malfunctioning script is arranged:

    1) I get existing value of $Article from database:
    $Article=$row['Article'];
    PHP:
    2) I revise $Article variable using htmlentities function:
    $Article=htmlentities($Article);
    PHP:
    3) I insert $Article into textarea field on form:
    <textarea name="Article"><?php echo $Article ?></textarea>
    PHP:
    4) I retrieve $Article variable on form target page after clicking "submit":
    $Article=$_REQUEST['Article'];
    
    PHP:
    5) I attempt to update the Article field in my database:
    $result=mysql_query("UPDATE MyTable SET Article = '$Article'");
    PHP:
    Again, the above procedure works fine if there are no apostrophes in the $Article variable that I submit, but if the $Article variable contains apostrophes, then the field will not update (or rather it will save all data up to the point where the first apostrophe occurs and then truncate the rest).


    Thanks in advance for any ideas on how to get my database to properly update fields containing apostrophes.

    Darden12
     
    Darden12, Mar 28, 2009 IP
  2. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #2
    Try changing the:
    
    $Article=htmlentities($Article);
    to
    $Article=mysql_real_escape_string($Article);
    
    PHP:
     
    PoPSiCLe, Mar 28, 2009 IP
  3. ads2help

    ads2help Peon

    Messages:
    2,142
    Likes Received:
    67
    Best Answers:
    1
    Trophy Points:
    0
    #3
    For Step 2, replace it with:

    $Article = stripslashes($Article);
    PHP:
    For Step 5, replace it with:

    
    $result=mysql_query("UPDATE MyTable SET Article = '".mysql_real_escape_string($Article)."'");
    PHP:
    or else your website can be easily hacked using SQL injection.

    - ads2help
     
    ads2help, Mar 29, 2009 IP
  4. Darden12

    Darden12 Well-Known Member

    Messages:
    107
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #4
    Thanks both of you for the suggestions. I got it to work using the "real escape string".
     
    Darden12, Mar 29, 2009 IP