Posted By

rickygri on 10/10/12


Tagged

mysql php pdo


Versions (?)

PDO Insert array function


 / Published in: PHP
 

URL: http://digipiph.com/blog/insert-mysql-pdo-function

PDO-format insert array function

  1. public function insert($table,$fields,$values) {
  2.  
  3. $db = $this->db_connect; // CONNECT
  4.  
  5. //build the fields
  6. $buildFields = '';
  7. if (is_array($fields)) {
  8. //loop through all the fields
  9. foreach($fields as $key => $field) {
  10. if ($key == 0) {
  11. //first item
  12. $buildFields .= $field;
  13. } else {
  14. //every other item follows with a ","
  15. $buildFields .= ', '.$field;
  16. }
  17. }
  18. } else {
  19. //we are only inserting one field
  20. $buildFields .= $fields;
  21. }
  22.  
  23. //build the values
  24. $buildValues = '';
  25. if (is_array($values)) {
  26. //loop through all the fields
  27. foreach($values as $key => $value) {
  28. if ($key == 0) {
  29. //first item
  30. $buildValues .= '?';
  31. } else {
  32. //every other item follows with a ","
  33. $buildValues .= ', ?';
  34. }
  35. }
  36. } else {
  37. //we are only inserting one field
  38. $buildValues .= ':value';
  39. }
  40.  
  41. $prepareInsert = $db->prepare('INSERT INTO '.$table.'('.$buildFields.') VALUES ('.$buildValues.')');
  42.  
  43. //execute the update for one or many values
  44. if (is_array($values)) {
  45. $prepareInsert->execute($values);
  46. } else {
  47. $prepareInsert->execute(array(':value' => $values));
  48. }
  49. //record and print any DB error that may be given
  50. $error = $prepareInsert->errorInfo();
  51. if ($error[1]) {
  52. print_r($error);
  53. } else {
  54. return true;
  55. }
  56.  
  57. }
  58.  
  59. // Use like this ->
  60.  
  61. // Change the line below to your timezone!
  62. date_default_timezone_set('Europe/London');
  63. $date = date('d-m-Y h:i:s a', time());
  64.  
  65. //inserting multiple items
  66. $fields[] = 'forename';
  67. $fields[] = 'surname';
  68. $fields[] = 'email';
  69. $fields[] = 'timestamp';
  70.  
  71. $values[] = "Rick";
  72. $values[] = "Grimaldi";
  73. $values[] = "[email protected]";
  74. $values[] = $date;
  75.  
  76.  
  77. if($db->insert('users', $fields, $values)) {
  78. echo "Success";
  79. } else {
  80. echo "Fail";
  81. }

Report this snippet  

You need to login to post a comment.