Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

PHP: Insert Data Into MySQL Table Using An Array

DZone's Guide to

PHP: Insert Data Into MySQL Table Using An Array

·
Free Resource
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;
}
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}