PHP Function: Escape post data before inserting into database


Here is a nice little function that I have been using for a while to convert my $_POST data into an object of slashed and trimmed values. I turn my values into objects so it makes a cleaner line of code when creating an insert statement.

function escapeSQL($datas = array())
{
  class rtn {};
  foreach( (array) $datas as $data => $val)
  {
    $rtn->$data = addslashes(trim($val));
  }
  return $rtn;
}

So when you submit a form to another php page to add the values to your database, it would looks something like this.

$post = escapeSQL($_POST);
$db->query("INSERT INTO table (title, body) VALUES ('$post->title', '$post->body')");