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: Update MySQL Table Using An Array

07.19.2007
| 21784 views |
  • submit to reddit
        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;
}