PDO插入数组函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PDO插入数组函数相关的知识,希望对你有一定的参考价值。

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. }

以上是关于PDO插入数组函数的主要内容,如果未能解决你的问题,请参考以下文章

PostgreSQL PDO 插入数组类型

PDO 将一个简单的数组插入 MySQL 数据库

使用 PDO 插入/更新辅助函数

JS数组到PHP并使用PDO更新MYSQL中的表

PDO json插入多个标签

重复密钥更新时的 PDO 插入