Over a million developers have joined DZone.

PHP: Update MySQL Table Using An Array

DZone's Guide to

PHP: Update MySQL Table Using An Array

Free Resource
Table: Name of table to update
Data: array of $field->$value with new values
Id Field: Name of field to use as ID field
Id Value: Value of ID field

function mysql_update_array($table, $data, $id_field, $id_value) {
	foreach ($data as $field=>$value) {
		$fields[] = sprintf("`%s` = '%s'", $field, mysql_real_escape_string($value));
	$field_list = join(',', $fields);
	$query = sprintf("UPDATE `%s` SET %s WHERE `%s` = %s", $table, $field_list, $id_field, intval($id_value));
	return $query;

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}