Search code examples
phpajaxhtmlspecialchars

Passing MySQL data through an ajax form via javascript/PHP with specialchars


I've recently thrown together a basic PHP webpage that lists information pulled from an MySQL table and displays it in various sorts. I'm wanting to allow the user to add a new item to the table, edit an item in the list and delete an item in the list without refreshing the page (Ajax).

This currently goes;

  • To add/edit an article you click on a link which prompts the popover ajax form, and fills it's contents (if editing) by performing the function setEdit(comment) as below;
  •    <a class="popup-button" title="<?php echo $row['comment']; ?>" onclick="setEdit('<?php if($row['comment']){ echo $row['comment']; } else { echo "Enter comment here..."; } ?>');"><?php echo $row['listitem']; ?></a>
    

  • The setEdit() comment is as follows;
  • function setEdit(editcomment)
    {
          if(editcomment){ document.getElementById('help-us-comment').value=editcomment; }
    }
    

  • Which is then, after submitting the ajax form, handled by the following php code;
  •  if(isset($_POST['comment_text']))
        $comment=$_POST['comment_text'];
    
        $sql = "INSERT INTO table SET
        comment='$comment'";
    

    Problem: I'm having constant issues trying to get the database contents through 1, 2, 3 without falling over at a new line, single or double quote. I've tried endless combinations of replacing tags, htmlspecialchars and nl2br with no half successes - where it's got to the point that it's so convoluted and encoded/decoded now that I'm assuming that there is a far simpler and obvious way that I'm missing.

    The main problem happens when trying to load the data into the form, typically having either the form fall over and refuse to populate at all (typically by the a link becoming broken by the data extracted i.e. single quote or new line) or the form being populated with special characters instead of plain text to edit.

    I've tried to go into as much detail as possible, but if any more is needed I'm happy to provide. Also apologies if this is an obvious fix/mistake, and I'm being an idiot.


    Solution

  • You have two problems here: storing and displaying.

    To display you should look in to htmlentities that makes it safe HTML (it does all the quotes replacing, html encoding, etc. for you) so that your string to be safe to be displayed as plain text, or as inputs' values.

    To store the data, you should sanitize your queries. You could use mysqli and bind parameters, or use mysql_real_escape_string to escape your input manually.

    Otherwise, say hi to Bobby Tables ;)