Last active
December 16, 2015 22:19
-
-
Save joshuaadickerson/5505890 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Update a row in multiple tables in the database | |
| * | |
| * @param string $identifier = '' | |
| * @param array|string $tables | |
| * @param array $columns | |
| * @param array $options = array() | |
| * @param resource $connection = null | |
| * | |
| * @return int the number of affected rows | |
| */ | |
| function smf_db_update($identifier = '', $tables, array $columns, array $options = array(), $connection = null) | |
| { | |
| global $smcFunc; | |
| $tables = is_array($tables) ? $tables : array($tables); | |
| if (empty($smcFunc['db_multi_table_update']) && count($tables) > 1) | |
| { | |
| $affected_rows = 0; | |
| foreach ($tables as $table) | |
| $affected_rows += smf_db_update($identifier, $table, $columns, $options); | |
| return $affected_rows; | |
| } | |
| $table_string = implode($tables, ', '); | |
| $values = array(); | |
| // Create the update query | |
| $query = 'UPDATE ' . (!empty($options['ignore']) ? 'IGNORE ' : '') . trim($table_string, ', ') . ' | |
| SET '; | |
| foreach ($columns as $col => $val) | |
| { | |
| $col = str_replace(array('{', '}'), '', $col); | |
| list($type, $col_name) = explode(':', $col); | |
| $values[$col_name] = $val; | |
| if (isset($options['swap'][$col_name])) | |
| { | |
| $set_value = $col_name . ($options['swap'][$col_name] > 0 ? ' + ' : '') . $options['swap'][$col_name]; | |
| } | |
| else | |
| $set_value = $col; | |
| $query .= ' | |
| ' . $col_name . ' = ' . $set_value . ','; | |
| } | |
| // Remove the last comma | |
| $query = substr($query, 0, -1); | |
| $query .= !empty($options['where']) ? "\n WHERE " . $options['where'] : ''; | |
| $query .= !empty($options['sort']) ? "\n ORDER BY " . $options['sort'] : ''; | |
| $query .= !empty($options['limit']) ? "\n LIMIT" . $options['limit'] : ''; | |
| $smcFunc['db_query']($identifier, $query, $values, $connection); | |
| return $smcFunc['db_affected_rows']($connection); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment