Revision: 59940
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at October 10, 2012 22:33 by rickygri
Initial Code
public function insert($table,$fields,$values) { $db = $this->db_connect; // CONNECT //build the fields $buildFields = ''; if (is_array($fields)) { //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 = ''; if (is_array($values)) { //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 if (is_array($values)) { $prepareInsert->execute($values); } else { $prepareInsert->execute(array(':value' => $values)); } //record and print any DB error that may be given $error = $prepareInsert->errorInfo(); if ($error[1]) { print_r($error); } else { return true; } } // Use like this -> // Change the line below to your timezone! date_default_timezone_set('Europe/London'); $date = date('d-m-Y h:i:s a', time()); //inserting multiple items $fields[] = 'forename'; $fields[] = 'surname'; $fields[] = 'email'; $fields[] = 'timestamp'; $values[] = "Rick"; $values[] = "Grimaldi"; $values[] = "[email protected]"; $values[] = $date; if($db->insert('users', $fields, $values)) { echo "Success"; } else { echo "Fail"; }
Initial URL
http://digipiph.com/blog/insert-mysql-pdo-function
Initial Description
PDO-format insert array function
Initial Title
PDO Insert array function
Initial Tags
mysql, php
Initial Language
PHP