Q:

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'");

A:

The proper way is using prepared statements, e.g. via PDO.
If you can't do that, you have to process all values which are passed into a database query with mysql_real_escape_string() - and no, doing that simply on all $_POST data is not an option since that would render them unusable for HTML output, etc. You could create a $_ESC or something similar though... but note that this variable will not be superglobal!

A:

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.

