PDO插入数组函数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PDO插入数组函数相关的知识,希望对你有一定的参考价值。
PDO-format insert array function
public function insert($table,$fields,$values) { $db = $this->db_connect; // CONNECT //build the fields $buildFields = ''; //loop through all the fields foreach($fields as $key => $field) { if ($key == 0) { //first item $buildFields .= $field; } else { //every other item follows with a "," $buildFields .= ', '.$field; } } } else { //we are only inserting one field $buildFields .= $fields; } //build the values $buildValues = ''; //loop through all the fields foreach($values as $key => $value) { if ($key == 0) { //first item $buildValues .= '?'; } else { //every other item follows with a "," $buildValues .= ', ?'; } } } else { //we are only inserting one field $buildValues .= ':value'; } $prepareInsert = $db->prepare('INSERT INTO '.$table.'('.$buildFields.') VALUES ('.$buildValues.')'); //execute the update for one or many values $prepareInsert->execute($values); } else { } //record and print any DB error that may be given $error = $prepareInsert->errorInfo(); if ($error[1]) { } else { return true; } } // Use like this -> // Change the line below to your timezone! //inserting multiple items $fields[] = 'forename'; $fields[] = 'surname'; $fields[] = 'email'; $fields[] = 'timestamp'; $values[] = "Rick"; $values[] = "Grimaldi"; $values[] = $date; if($db->insert('users', $fields, $values)) { echo "Success"; } else { echo "Fail"; }
以上是关于PDO插入数组函数的主要内容,如果未能解决你的问题,请参考以下文章