Home >> Snippet List >> Snippet

Update MySQL Table Using An Array
Iterate over an array and update a mySQL table
PHP Snippet
// 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;