Over a million developers have joined DZone.

PHP: Update MySQL Table Using An Array

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

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

{{ parent.tldr }}

{{ parent.urlSource.name }}