3.4.3 release
[phpmyadmin/madhuracj.git] / tbl_replace.php
blob2876b5051807e8645857d77aef8ab42df843ad8b
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * manipulation of table data like inserting, replacing and updating
6 * usally called as form action from tbl_change.php to insert or update table rows
9 * @todo 'edit_next' tends to not work as expected if used ... at least there is no order by
10 * it needs the original query and the row number and than replace the LIMIT clause
11 * @package phpMyAdmin
14 /**
15 * do not import request variable into global scope
17 * cannot be used as long as it could happen that the $goto file that is included
18 * at the end of this script is not updated to work without imported request variables
20 * @todo uncomment this if all possible included files to rely on import request variables
21 if (! defined('PMA_NO_VARIABLES_IMPORT')) {
22 define('PMA_NO_VARIABLES_IMPORT', true);
25 /**
26 * Gets some core libraries
28 require_once './libraries/common.inc.php';
29 $blob_streaming_active = $GLOBALS['PMA_Config']->get('BLOBSTREAMING_PLUGINS_EXIST');
31 // Check parameters
32 PMA_checkParameters(array('db', 'table', 'goto'));
34 PMA_DBI_select_db($GLOBALS['db']);
36 /**
37 * Initializes some variables
39 $goto_include = false;
41 $GLOBALS['js_include'][] = 'makegrid.js';
42 // Needed for generation of Inline Edit anchors
43 $GLOBALS['js_include'][] = 'sql.js';
45 if (isset($_REQUEST['insert_rows']) && is_numeric($_REQUEST['insert_rows']) && $_REQUEST['insert_rows'] != $cfg['InsertRows']) {
46 $cfg['InsertRows'] = $_REQUEST['insert_rows'];
47 $GLOBALS['js_include'][] = 'tbl_change.js';
48 require_once './libraries/header.inc.php';
49 require './tbl_change.php';
50 exit;
53 if (isset($_REQUEST['after_insert'])
54 && in_array($_REQUEST['after_insert'], array('new_insert', 'same_insert', 'edit_next'))) {
55 $url_params['after_insert'] = $_REQUEST['after_insert'];
56 //$GLOBALS['goto'] = 'tbl_change.php';
57 $goto_include = 'tbl_change.php';
59 if (isset($_REQUEST['where_clause'])) {
60 if ($_REQUEST['after_insert'] == 'same_insert') {
61 foreach ($_REQUEST['where_clause'] as $one_where_clause) {
62 $url_params['where_clause'][] = $one_where_clause;
64 } elseif ($_REQUEST['after_insert'] == 'edit_next') {
65 foreach ($_REQUEST['where_clause'] as $one_where_clause) {
66 $local_query = 'SELECT * FROM ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
67 . ' WHERE ' . str_replace('` =', '` >', $one_where_clause)
68 . ' LIMIT 1;';
69 $res = PMA_DBI_query($local_query);
70 $row = PMA_DBI_fetch_row($res);
71 $meta = PMA_DBI_get_fields_meta($res);
72 // must find a unique condition based on unique key,
73 // not a combination of all fields
74 list($unique_condition, $clause_is_unique) = PMA_getUniqueCondition($res, count($meta), $meta, $row, true);
75 if (! empty($unique_condition)) {
76 $_SESSION['edit_next'] = $unique_condition;
78 unset($unique_condition, $clause_is_unique);
82 } elseif (! empty($GLOBALS['goto'])) {
83 if (! preg_match('@^[a-z_]+\.php$@', $GLOBALS['goto'])) {
84 // this should NOT happen
85 //$GLOBALS['goto'] = false;
86 $goto_include = false;
87 } else {
88 $goto_include = $GLOBALS['goto'];
90 if ($GLOBALS['goto'] == 'db_sql.php' && strlen($GLOBALS['table'])) {
91 $GLOBALS['table'] = '';
95 if (! $goto_include) {
96 if (! strlen($GLOBALS['table'])) {
97 $goto_include = 'db_sql.php';
98 } else {
99 $goto_include = 'tbl_sql.php';
103 // Defines the url to return in case of failure of the query
104 if (isset($_REQUEST['err_url'])) {
105 $err_url = $_REQUEST['err_url'];
106 } else {
107 $err_url = 'tbl_change.php' . PMA_generate_common_url($url_params);
111 * Prepares the update/insert of a row
113 if (isset($_REQUEST['where_clause'])) {
114 // we were editing something => use the WHERE clause
115 $loop_array = (is_array($_REQUEST['where_clause']) ? $_REQUEST['where_clause'] : array($_REQUEST['where_clause']));
116 $using_key = true;
117 $is_insert = ($_REQUEST['submit_type'] == 'insert') || ($_REQUEST['submit_type'] == 'showinsert') || ($_REQUEST['submit_type'] == 'insertignore');
118 $is_insertignore = ($_REQUEST['submit_type'] == 'insertignore');
119 } else {
120 // new row => use indexes
121 $loop_array = array();
122 foreach ($_REQUEST['fields']['multi_edit'] as $key => $dummy) {
123 $loop_array[] = $key;
125 $using_key = false;
126 $is_insert = true;
127 $is_insertignore = false;
130 $query = array();
131 $value_sets = array();
132 $func_no_param = array(
133 'NOW',
134 'CURDATE',
135 'CURTIME',
136 'UTC_DATE',
137 'UTC_TIME',
138 'UTC_TIMESTAMP',
139 'UNIX_TIMESTAMP',
140 'RAND',
141 'USER',
142 'LAST_INSERT_ID',
143 'UUID',
144 'CURRENT_USER',
147 foreach ($loop_array as $rownumber => $where_clause) {
148 // skip fields to be ignored
149 if (! $using_key && isset($_REQUEST['insert_ignore_' . $where_clause])) {
150 continue;
153 // Defines the SET part of the sql query
154 $query_values = array();
156 // Map multi-edit keys to single-level arrays, dependent on how we got the fields
157 $me_fields =
158 isset($_REQUEST['fields']['multi_edit'][$rownumber])
159 ? $_REQUEST['fields']['multi_edit'][$rownumber]
160 : array();
161 $me_fields_name =
162 isset($_REQUEST['fields_name']['multi_edit'][$rownumber])
163 ? $_REQUEST['fields_name']['multi_edit'][$rownumber]
164 : null;
165 $me_fields_prev =
166 isset($_REQUEST['fields_prev']['multi_edit'][$rownumber])
167 ? $_REQUEST['fields_prev']['multi_edit'][$rownumber]
168 : null;
169 $me_funcs =
170 isset($_REQUEST['funcs']['multi_edit'][$rownumber])
171 ? $_REQUEST['funcs']['multi_edit'][$rownumber]
172 : null;
173 $me_fields_type =
174 isset($_REQUEST['fields_type']['multi_edit'][$rownumber])
175 ? $_REQUEST['fields_type']['multi_edit'][$rownumber]
176 : null;
177 $me_fields_null =
178 isset($_REQUEST['fields_null']['multi_edit'][$rownumber])
179 ? $_REQUEST['fields_null']['multi_edit'][$rownumber]
180 : null;
181 $me_fields_null_prev =
182 isset($_REQUEST['fields_null_prev']['multi_edit'][$rownumber])
183 ? $_REQUEST['fields_null_prev']['multi_edit'][$rownumber]
184 : null;
185 $me_auto_increment =
186 isset($_REQUEST['auto_increment']['multi_edit'][$rownumber])
187 ? $_REQUEST['auto_increment']['multi_edit'][$rownumber]
188 : null;
190 // Fetch the current values of a row to use in case we have a protected field
191 // @todo possibly move to ./libraries/tbl_replace_fields.inc.php
192 if ($is_insert && $using_key && isset($me_fields_type) && is_array($me_fields_type) && isset($where_clause)) {
193 $prot_row = PMA_DBI_fetch_single_row('SELECT * FROM ' . PMA_backquote($table) . ' WHERE ' . $where_clause . ';');
195 foreach ($me_fields as $key => $val) {
197 // Note: $key is an md5 of the fieldname. The actual fieldname is available in $me_fields_name[$key]
199 require './libraries/tbl_replace_fields.inc.php';
201 // for blobstreaming
202 if ($blob_streaming_active) {
203 $remove_blob_repo = isset($_REQUEST['remove_blob_repo_' . $key]) ? $_REQUEST['remove_blob_repo_' . $key] : NULL;
204 $upload_blob_repo = isset($_REQUEST['upload_blob_repo_' . $key]) ? $_REQUEST['upload_blob_repo_' . $key] : NULL;
206 // checks if an existing blob repository reference should be removed
207 if (isset($remove_blob_repo) && ! isset($upload_blob_repo)) {
208 $remove_blob_reference = $_REQUEST['remove_blob_ref_' . $key];
209 if (isset($remove_blob_reference)) {
210 $val = "NULL";
214 // checks if this field requires a bs reference attached to it
215 if (isset($upload_blob_repo)) {
216 // get the most recent BLOB reference
217 $bs_reference = PMA_File::getRecentBLOBReference();
219 // if the most recent BLOB reference exists, set it as a field value
220 if (!is_null($bs_reference)) {
221 $val = "'" . PMA_sqlAddslashes($bs_reference) . "'";
226 if (empty($me_funcs[$key])) {
227 $cur_value = $val;
228 } elseif ('UNIX_TIMESTAMP' === $me_funcs[$key] && $val != "''") {
229 $cur_value = $me_funcs[$key] . '(' . $val . ')';
230 } elseif ('UUID' === $me_funcs[$key]) {
231 /* This way user will know what UUID new row has */
232 $uuid = PMA_DBI_fetch_value('SELECT UUID()');
233 $cur_value = "'" . $uuid . "'";
234 } elseif (in_array($me_funcs[$key], $func_no_param)) {
235 $cur_value = $me_funcs[$key] . '()';
236 } else {
237 $cur_value = $me_funcs[$key] . '(' . $val . ')';
240 // i n s e r t
241 if ($is_insert) {
242 // no need to add column into the valuelist
243 if (strlen($cur_value)) {
244 $query_values[] = $cur_value;
245 // first inserted row so prepare the list of fields
246 if (empty($value_sets)) {
247 $query_fields[] = PMA_backquote($me_fields_name[$key]);
251 // u p d a t e
252 } elseif (!empty($me_fields_null_prev[$key])
253 && ! isset($me_fields_null[$key])) {
254 // field had the null checkbox before the update
255 // field no longer has the null checkbox
256 $query_values[] = PMA_backquote($me_fields_name[$key]) . ' = ' . $cur_value;
257 } elseif (empty($me_funcs[$key])
258 && isset($me_fields_prev[$key])
259 && ("'" . PMA_sqlAddslashes($me_fields_prev[$key]) . "'" == $val)) {
260 // No change for this column and no MySQL function is used -> next column
261 continue;
262 } elseif (! empty($val)) {
263 // avoid setting a field to NULL when it's already NULL
264 // (field had the null checkbox before the update
265 // field still has the null checkbox)
266 if (!(! empty($me_fields_null_prev[$key])
267 && isset($me_fields_null[$key]))) {
268 $query_values[] = PMA_backquote($me_fields_name[$key]) . ' = ' . $cur_value;
271 } // end foreach ($me_fields as $key => $val)
273 if (count($query_values) > 0) {
274 if ($is_insert) {
275 $value_sets[] = implode(', ', $query_values);
276 } else {
277 // build update query
278 $query[] = 'UPDATE ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
279 . ' SET ' . implode(', ', $query_values) . ' WHERE ' . $where_clause . ($_REQUEST['clause_is_unique'] ? '' : ' LIMIT 1');
283 } // end foreach ($loop_array as $where_clause)
284 unset($me_fields_name, $me_fields_prev, $me_funcs, $me_fields_type, $me_fields_null, $me_fields_null_prev,
285 $me_auto_increment, $cur_value, $key, $val, $loop_array, $where_clause, $using_key,
286 $func_no_param);
289 // Builds the sql query
290 if ($is_insert && count($value_sets) > 0) {
291 if ($is_insertignore) {
292 $insert_command = 'INSERT IGNORE ';
293 } else {
294 $insert_command = 'INSERT ';
296 $query[] = $insert_command . 'INTO ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($GLOBALS['table'])
297 . ' (' . implode(', ', $query_fields) . ') VALUES (' . implode('), (', $value_sets) . ')';
298 unset($insert_command);
300 unset($query_fields);
301 } elseif (empty($query)) {
302 // No change -> move back to the calling script
304 // Note: logic passes here for inline edit
305 $message = PMA_Message::success(__('No change'));
306 $active_page = $goto_include;
307 if(! $GLOBALS['is_ajax_request'] == true) {
308 require_once './libraries/header.inc.php';
310 require './' . PMA_securePath($goto_include);
311 exit;
313 unset($me_fields, $is_insertignore);
316 * Executes the sql query and get the result, then move back to the calling
317 * page
319 if (! empty($GLOBALS['sql_query'])) {
320 $url_params['sql_query'] = $GLOBALS['sql_query'];
321 $return_to_sql_query = $GLOBALS['sql_query'];
323 $GLOBALS['sql_query'] = implode('; ', $query) . ';';
324 // to ensure that the query is displayed in case of
325 // "insert as new row" and then "insert another new row"
326 $GLOBALS['display_query'] = $GLOBALS['sql_query'];
328 $total_affected_rows = 0;
329 $last_messages = array();
330 $warning_messages = array();
331 $error_messages = array();
333 foreach ($query as $single_query) {
334 if ($_REQUEST['submit_type'] == 'showinsert') {
335 $last_messages[] = PMA_Message::notice(__('Showing SQL query'));
336 continue;
338 if ($GLOBALS['cfg']['IgnoreMultiSubmitErrors']) {
339 $result = PMA_DBI_try_query($single_query);
340 } else {
341 $result = PMA_DBI_query($single_query);
344 if (! $result) {
345 $error_messages[] = PMA_DBI_getError();
346 } else {
347 // The next line contains a real assignment, it's not a typo
348 if ($tmp = @PMA_DBI_affected_rows()) {
349 $total_affected_rows += $tmp;
351 unset($tmp);
353 $insert_id = PMA_DBI_insert_id();
354 if ($insert_id != 0) {
355 // insert_id is id of FIRST record inserted in one insert, so if we
356 // inserted multiple rows, we had to increment this
358 if ($total_affected_rows > 0) {
359 $insert_id = $insert_id + $total_affected_rows - 1;
361 $last_message = PMA_Message::notice(__('Inserted row id: %1$d'));
362 $last_message->addParam($insert_id);
363 $last_messages[] = $last_message;
365 PMA_DBI_free_result($result);
366 } // end if
368 foreach (PMA_DBI_get_warnings() as $warning) {
369 $warning_messages[] = $warning['Level'] . ': #' . $warning['Code']
370 . ' ' . $warning['Message'];
373 unset($result);
375 unset($single_query, $query);
377 if ($is_insert && count($value_sets) > 0) {
378 $message = PMA_Message::inserted_rows($total_affected_rows);
379 } else {
380 $message = PMA_Message::affected_rows($total_affected_rows);
383 $message->addMessages($last_messages, '<br />');
385 if (! empty($warning_messages)) {
387 * @todo use a <div class="error"> in PMA_showMessage() for this part of
388 * the message
390 $message->addMessages($warning_messages, '<br />');
391 $message->isError(true);
393 if (! empty($error_messages)) {
394 $message->addMessages($error_messages);
395 $message->isError(true);
397 unset($error_messages, $warning_messages, $total_affected_rows, $last_messages, $last_message);
399 if($GLOBALS['is_ajax_request'] == true) {
400 /**Get the total row count of the table*/
401 $extra_data['row_count'] = PMA_Table::countRecords($_REQUEST['db'],$_REQUEST['table']);
402 $extra_data['sql_query'] = PMA_showMessage(NULL, $GLOBALS['display_query']);
403 PMA_ajaxResponse($message, $message->isSuccess(), $extra_data);
406 if (isset($return_to_sql_query)) {
407 $disp_query = $GLOBALS['sql_query'];
408 $disp_message = $message;
409 unset($message);
410 $GLOBALS['sql_query'] = $return_to_sql_query;
413 $GLOBALS['js_include'][] = 'tbl_change.js';
414 // in case we call sql.php which needs those:
415 $GLOBALS['js_include'][] = 'jquery/jquery-ui-1.8.custom.js';
417 $active_page = $goto_include;
420 * If user asked for "and then Insert another new row" we have to remove
421 * WHERE clause information so that tbl_change.php does not go back
422 * to the current record
424 if (isset($_REQUEST['after_insert']) && 'new_insert' == $_REQUEST['after_insert']) {
425 unset($_REQUEST['where_clause']);
429 * Load header.
431 require_once './libraries/header.inc.php';
433 * Load target page.
435 require './' . PMA_securePath($goto_include);
436 exit;