/ Published in: PHP
PDO-format insert array function
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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"; }
URL: http://digipiph.com/blog/insert-mysql-pdo-function