phpaddslashes

Escaping quotes in PHP


How do I escape quotes in PHP when trying to query a MySQL database?

Without adding addslashes on every value:

$fname = addslashes("Value's with quote''s'");
$lname = addslashes("Value's with quote''s'");

Solution

  • You ought to escape special characters (not only quotes) on every string value (it's useless to escape values you're not going to enclose in quotes in a query. Those values require another treatment).

    To avoid boring repetitive typing you can apply an escaping function to array items in a loop.

    In case you're using MySQL and for INSERT/UPDATE queries, you can use this helper function:

    function dbSet($fields) {
      $set = '';
      foreach ($fields as $field) {
        if (isset($_POST[$field])) {
          $set .= "`$field`='" . mysql_real_escape_string($_POST[$field]) . "', ";
        }
      }
      return substr($set, 0, -2); 
    }
    

    It is used like this:

    $id     = intval($_POST['id']);
    $table  = 'users';
    $fields = explode(" ","name surname lastname address zip fax phone");
    $query  = "UPDATE `$table` SET ".dbSet($fields).", `date`=NOW() WHERE id=$id";
    

    Also don't forget to set proper encoding using mysql_set_charset() as it's required for the mysql_real_escape_string() function.