DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Arthur has posted 13 posts at DZone. View Full User Profile

PHP: Insert Data Into MySQL Table Using An Array

07.23.2007
| 53555 views |
  • submit to reddit
        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)

function mysql_insert_array($table, $data, $password_field = "") {
	foreach ($data as $field=>$value) {
		$fields[] = '`' . $field . '`';
		
		if ($field == $password_field) {
			$values[] = "PASSWORD('" . mysql_real_escape_string($value) . "')";
		} else {
			$values[] = "'" . mysql_real_escape_string($value) . "'";
		}
	}
	$field_list = join(',', $fields);
	$value_list = join(', ', $values);
	
	$query = "INSERT INTO `" . $table . "` (" . $field_list . ") VALUES (" . $value_list . ")";
	
	return $query;
}