How to prevent MySQL injection in forms?

Discussion in 'Databases' started by wryfhk22, Apr 8, 2011.

  1. #1
    Hi,

    How can I prevent MySQL injection in text fields and forms? Can someone provide a code example?

    Is it basically taking commas out of the user input?

    Thanks,
     
    wryfhk22, Apr 8, 2011 IP
  2. crivion

    crivion Notable Member

    Messages:
    1,669
    Likes Received:
    45
    Best Answers:
    0
    Trophy Points:
    210
    Digital Goods:
    3
    #2
    it's not taking commas, it's escaping stuff like single quote '
    mysql_real_escape_string($_POST['form_input_name'])
     
    crivion, Apr 8, 2011 IP
  3. opx

    opx Greenhorn

    Messages:
    44
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #3
    mostly happens on integer variables, so make sure you get an integer from an user instead of text.
     
    opx, Apr 9, 2011 IP
  4. x319

    x319 Well-Known Member

    Messages:
    90
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    103
    #4
    You can do tests based on what you expect the input to be, and what crivion said is a really good call before you test.

    Just remember never to use raw input data collected by the form (test the value before sending it through SQL)
     
    x319, Apr 10, 2011 IP
  5. EitanXOR

    EitanXOR Greenhorn

    Messages:
    30
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #5
    I would suggest you to read up about PHP's PDO (php.net/pdo). It allows you to insert dynamic content to SQL queries using a sort of placeholders, so that the database library takes care of all the escaping for you.
     
    EitanXOR, Apr 16, 2011 IP