Simple PDO Insert method


/ Published in: PHP
Save to your folder(s)

Simple method to insert data to sql


Copy this code and paste it in your HTML
  1. // Build the field:value array
  2. $in = array();
  3. $in['fieldname'] = 'Value';
  4. $in['fieldname2'] = 'Value 2';
  5.  
  6. // Insert into db
  7. $db->insert('tablename', $in);
  8.  
  9. // Method:
  10. public function insert($table, $data)
  11. {
  12. ksort($data);
  13. $fieldnames = '`'.implode('`, `', array_keys($data)).'`';
  14. $fieldvalues = ':'.implode(', :', array_keys($data));
  15.  
  16. $SQL = "INSERT INTO `{$table}` ({$fieldnames}) VALUES ({$fieldvalues})";
  17. $sth = $this->prepare($SQL);
  18. return $sth->execute($data);
  19. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.