Posted By

BergBenji on 10/22/12


Tagged

mysql php pdo


Versions (?)

Simple PDO Insert method


 / Published in: PHP
 

Simple method to insert data to sql

  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  

You need to login to post a comment.