Posted By

depmed on 08/24/07


Tagged

php


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

heinz1959
bsisco
Nix


PHP: Insert Data Into MySQL Table Using An Array [mysql] [php] [array] [INSERT]


 / Published in: PHP
 

URL: http://snippets.dzone.com/posts/show/4350

Inserts the values of an array into a table. Also supports specifying if a specific field needs to be encoded using PASSWORD() Parameters: Table: Name of table to insert into Data: array of $field->$value of new data Password Field: Which field in the data array needs to be surrounded with PASSWORD() (optional)

  1. function mysql_insert_array($table, $data, $password_field = "") {
  2. foreach ($data as $field=>$value) {
  3. $fields[] = '`' . $field . '`';
  4.  
  5. if ($field == $password_field) {
  6. $values[] = "PASSWORD('" . mysql_real_escape_string($value) . "')";
  7. } else {
  8. $values[] = "'" . mysql_real_escape_string($value) . "'";
  9. }
  10. }
  11. $field_list = join(',', $fields);
  12. $value_list = join(', ', $values);
  13.  
  14. $query = "INSERT INTO `" . $table . "` (" . $field_list . ") VALUES (" . $value_list . ")";
  15.  
  16. return $query;
  17. }

Report this snippet  

You need to login to post a comment.