Пример #1
0
/**
 * Get the column details of VIEW with its original references
 *
 * @param string $sql_query    SQL for original resource
 * @param array  $view_columns Columns of VIEW if defined new column names
 *
 * @return array $column_map Details of VIEW columns
 */
function PMA_getColumnMap($sql_query, $view_columns)
{
    $column_map = array();
    // Select query which give results for VIEW
    $real_source_result = PMA_DBI_try_query($sql_query);
    if ($real_source_result !== false) {
        $real_source_fields_meta = PMA_DBI_get_fields_meta($real_source_result);
        if (count($real_source_fields_meta) > 0) {
            for ($i = 0; $i < count($real_source_fields_meta); $i++) {
                $map = array();
                $map['table_name'] = $real_source_fields_meta[$i]->table;
                $map['refering_column'] = $real_source_fields_meta[$i]->name;
                if (count($view_columns) > 1) {
                    $map['real_column'] = $view_columns[$i];
                }
                $column_map[] = $map;
            }
        }
    }
    unset($real_source_result);
    return $column_map;
}
Пример #2
0
 /**
  * Dispatches between the versions of 'getTableContent' to use depending
  * on the php version
  *
  * @param   string      the database name
  * @param   string      the table name
  * @param   string      the end of line sequence
  * @param   string      the url to go back in case of error
  * @param   string      SQL query for obtaining data
  *
  * @return  bool        Whether it suceeded
  *
  * @global  boolean  whether to use backquotes to allow the use of special
  *                   characters in database, table and fields names or not
  * @global  integer  the number of records
  * @global  integer  the current record position
  *
  * @access  public
  *
  * @see     PMA_getTableContentFast(), PMA_getTableContentOld()
  *
  * @author  staybyte
  */
 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
 {
     global $sql_backquotes;
     global $rows_cnt;
     global $current_row;
     $formatted_table_name = isset($GLOBALS['sql_backquotes']) ? PMA_backquote($table) : '\'' . $table . '\'';
     // Do not export data for a VIEW
     // (For a VIEW, this is called only when exporting a single VIEW)
     if (PMA_Table::_isView($db, $table)) {
         $head = $crlf . PMA_exportComment() . PMA_exportComment('VIEW ' . ' ' . $formatted_table_name) . PMA_exportComment($GLOBALS['strData'] . ': ' . $GLOBALS['strNone']) . PMA_exportComment() . $crlf;
         if (!PMA_exportOutputHandler($head)) {
             return FALSE;
         }
         return true;
     }
     // it's not a VIEW
     $head = $crlf . PMA_exportComment() . PMA_exportComment($GLOBALS['strDumpingData'] . ' ' . $formatted_table_name) . PMA_exportComment() . $crlf;
     if (!PMA_exportOutputHandler($head)) {
         return FALSE;
     }
     $buffer = '';
     // analyze the query to get the true column names, not the aliases
     // (this fixes an undefined index, also if Complete inserts
     //  are used, we did not get the true column name in case of aliases)
     $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query));
     $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
     if ($result != FALSE) {
         $fields_cnt = PMA_DBI_num_fields($result);
         // Get field information
         $fields_meta = PMA_DBI_get_fields_meta($result);
         $field_flags = array();
         for ($j = 0; $j < $fields_cnt; $j++) {
             $field_flags[$j] = PMA_DBI_field_flags($result, $j);
         }
         for ($j = 0; $j < $fields_cnt; $j++) {
             if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) {
                 $field_set[$j] = PMA_backquote($analyzed_sql[0]['select_expr'][$j]['column'], $sql_backquotes);
             } else {
                 $field_set[$j] = PMA_backquote($fields_meta[$j]->name, $sql_backquotes);
             }
         }
         if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
             // update
             $schema_insert = 'UPDATE ';
             if (isset($GLOBALS['sql_ignore'])) {
                 $schema_insert .= 'IGNORE ';
             }
             // avoid EOL blank
             $schema_insert .= PMA_backquote($table, $sql_backquotes) . ' SET';
         } else {
             // insert or replace
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'REPLACE') {
                 $sql_command = 'REPLACE';
             } else {
                 $sql_command = 'INSERT';
             }
             // delayed inserts?
             if (isset($GLOBALS['sql_delayed'])) {
                 $insert_delayed = ' DELAYED';
             } else {
                 $insert_delayed = '';
             }
             // insert ignore?
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'INSERT' && isset($GLOBALS['sql_ignore'])) {
                 $insert_delayed .= ' IGNORE';
             }
             // scheme for inserting fields
             if (isset($GLOBALS['sql_columns'])) {
                 $fields = implode(', ', $field_set);
                 $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_backquote($table, $sql_backquotes) . ' (' . $fields . ') VALUES';
             } else {
                 $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_backquote($table, $sql_backquotes) . ' VALUES';
             }
         }
         $search = array("", "\n", "\r", "");
         //\x08\\x09, not required
         $replace = array('\\0', '\\n', '\\r', '\\Z');
         $current_row = 0;
         $query_size = 0;
         if (isset($GLOBALS['sql_extended']) && (!isset($GLOBALS['sql_type']) || $GLOBALS['sql_type'] != 'UPDATE')) {
             $separator = ',';
             $schema_insert .= $crlf;
         } else {
             $separator = ';';
         }
         while ($row = PMA_DBI_fetch_row($result)) {
             $current_row++;
             for ($j = 0; $j < $fields_cnt; $j++) {
                 // NULL
                 if (!isset($row[$j]) || is_null($row[$j])) {
                     $values[] = 'NULL';
                     // a number
                     // timestamp is numeric on some MySQL 4.1, BLOBs are sometimes numeric
                 } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp' && !$fields_meta[$j]->blob) {
                     $values[] = $row[$j];
                     // a true BLOB
                     // - mysqldump only generates hex data when the --hex-blob
                     //   option is used, for fields having the binary attribute
                     //   no hex is generated
                     // - a TEXT field returns type blob but a real blob
                     //   returns also the 'binary' flag
                 } elseif (stristr($field_flags[$j], 'BINARY') && $fields_meta[$j]->blob && isset($GLOBALS['sql_hex_for_blob'])) {
                     // empty blobs need to be different, but '0' is also empty :-(
                     if (empty($row[$j]) && $row[$j] != '0') {
                         $values[] = '\'\'';
                     } else {
                         $values[] = '0x' . bin2hex($row[$j]);
                     }
                     // detection of 'bit' works only on mysqli extension
                 } elseif ($fields_meta[$j]->type == 'bit') {
                     $values[] = "b'" . PMA_sqlAddslashes(PMA_printable_bit_value($row[$j], $fields_meta[$j]->length)) . "'";
                     // something else -> treat as a string
                 } else {
                     $values[] = '\'' . str_replace($search, $replace, PMA_sqlAddslashes($row[$j])) . '\'';
                 }
                 // end if
             }
             // end for
             // should we make update?
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
                 $insert_line = $schema_insert;
                 for ($i = 0; $i < $fields_cnt; $i++) {
                     if (0 == $i) {
                         $insert_line .= ' ';
                     }
                     if ($i > 0) {
                         // avoid EOL blank
                         $insert_line .= ',';
                     }
                     $insert_line .= $field_set[$i] . ' = ' . $values[$i];
                 }
                 $insert_line .= ' WHERE ' . PMA_getUniqueCondition($result, $fields_cnt, $fields_meta, $row);
             } else {
                 // Extended inserts case
                 if (isset($GLOBALS['sql_extended'])) {
                     if ($current_row == 1) {
                         $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
                     } else {
                         $insert_line = '(' . implode(', ', $values) . ')';
                         if (isset($GLOBALS['sql_max_query_size']) && $GLOBALS['sql_max_query_size'] > 0 && $query_size + strlen($insert_line) > $GLOBALS['sql_max_query_size']) {
                             if (!PMA_exportOutputHandler(';' . $crlf)) {
                                 return FALSE;
                             }
                             $query_size = 0;
                             $current_row = 1;
                             $insert_line = $schema_insert . $insert_line;
                         }
                     }
                     $query_size += strlen($insert_line);
                 } else {
                     $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
                 }
             }
             unset($values);
             if (!PMA_exportOutputHandler(($current_row == 1 ? '' : $separator . $crlf) . $insert_line)) {
                 return FALSE;
             }
         }
         // end while
         if ($current_row > 0) {
             if (!PMA_exportOutputHandler(';' . $crlf)) {
                 return FALSE;
             }
         }
     }
     // end if ($result != FALSE)
     PMA_DBI_free_result($result);
     return TRUE;
 }
Пример #3
0
/**
 * Generate table html when SQL statement have multiple queries
 * which return displayable results
 *
 * @param PMA_DisplayResults $displayResultsObject object
 * @param string             $db                   database name
 * @param array              $sql_data             information about SQL statement
 * @param string             $goto                 URL to go back in case of errors
 * @param string             $pmaThemeImage        path for theme images directory
 * @param string             $text_dir             text direction
 * @param string             $printview            whether printview is enabled
 * @param string             $url_query            URL query
 * @param array              $disp_mode            the display mode
 * @param string             $sql_limit_to_append  limit clause
 * @param bool               $editable             whether result set is editable
 *
 * @return string   $table_html   html content
 */
function getTableHtmlForMultipleQueries($displayResultsObject, $db, $sql_data, $goto, $pmaThemeImage, $text_dir, $printview, $url_query, $disp_mode, $sql_limit_to_append, $editable)
{
    $table_html = '';
    $tables_array = PMA_DBI_get_tables($db);
    $databases_array = PMA_DBI_get_databases_full();
    $multi_sql = implode(";", $sql_data['valid_sql']);
    $querytime_before = array_sum(explode(' ', microtime()));
    // Assignment for variable is not needed since the results are
    // looiping using the connection
    @PMA_DBI_try_multi_query($multi_sql);
    $querytime_after = array_sum(explode(' ', microtime()));
    $querytime = $querytime_after - $querytime_before;
    $sql_no = 0;
    do {
        $analyzed_sql = array();
        $is_affected = false;
        $result = PMA_DBI_store_result();
        $fields_meta = $result !== false ? PMA_DBI_get_fields_meta($result) : array();
        $fields_cnt = count($fields_meta);
        // Initialize needed params related to each query in multiquery statement
        if (isset($sql_data['valid_sql'][$sql_no])) {
            // 'Use' query can change the database
            if (stripos($sql_data['valid_sql'][$sql_no], "use ")) {
                $db = PMA_getNewDatabase($sql_data['valid_sql'][$sql_no], $databases_array);
            }
            $parsed_sql = PMA_SQP_parse($sql_data['valid_sql'][$sql_no]);
            $table = PMA_getTableNameBySQL($sql_data['valid_sql'][$sql_no], $tables_array);
            $analyzed_sql = PMA_SQP_analyze($parsed_sql);
            $is_select = isset($analyzed_sql[0]['queryflags']['select_from']);
            $unlim_num_rows = PMA_Table::countRecords($db, $table, true);
            $showtable = PMA_Table::sGetStatusInfo($db, $table, null, true);
            $url_query = PMA_generate_common_url($db, $table);
            list($is_group, $is_func, $is_count, $is_export, $is_analyse, $is_explain, $is_delete, $is_affected, $is_insert, $is_replace, $is_show, $is_maint) = PMA_getDisplayPropertyParams($sql_data['valid_sql'][$sql_no], $is_select);
            // Handle remembered sorting order, only for single table query
            if ($GLOBALS['cfg']['RememberSorting'] && !($is_count || $is_export || $is_func || $is_analyse) && isset($analyzed_sql[0]['select_expr']) && count($analyzed_sql[0]['select_expr']) == 0 && isset($analyzed_sql[0]['queryflags']['select_from']) && count($analyzed_sql[0]['table_ref']) == 1) {
                PMA_handleSortOrder($db, $table, $analyzed_sql, $sql_data['valid_sql'][$sql_no]);
            }
            // Do append a "LIMIT" clause?
            if ($_SESSION['tmp_user_values']['max_rows'] != 'all' && !($is_count || $is_export || $is_func || $is_analyse) && isset($analyzed_sql[0]['queryflags']['select_from']) && !isset($analyzed_sql[0]['queryflags']['offset']) && empty($analyzed_sql[0]['limit_clause'])) {
                $sql_limit_to_append = ' LIMIT ' . $_SESSION['tmp_user_values']['pos'] . ', ' . $_SESSION['tmp_user_values']['max_rows'] . " ";
                $sql_data['valid_sql'][$sql_no] = PMA_getSqlWithLimitClause($sql_data['valid_sql'][$sql_no], $analyzed_sql, $sql_limit_to_append);
            }
            // Set the needed properties related to executing sql query
            $displayResultsObject->__set('db', $db);
            $displayResultsObject->__set('table', $table);
            $displayResultsObject->__set('goto', $goto);
        }
        if (!$is_affected) {
            $num_rows = $result ? @PMA_DBI_num_rows($result) : 0;
        } elseif (!isset($num_rows)) {
            $num_rows = @PMA_DBI_affected_rows();
        }
        if (isset($sql_data['valid_sql'][$sql_no])) {
            $displayResultsObject->__set('sql_query', $sql_data['valid_sql'][$sql_no]);
            $displayResultsObject->setProperties($unlim_num_rows, $fields_meta, $is_count, $is_export, $is_func, $is_analyse, $num_rows, $fields_cnt, $querytime, $pmaThemeImage, $text_dir, $is_maint, $is_explain, $is_show, $showtable, $printview, $url_query, $editable);
        }
        if ($num_rows == 0) {
            continue;
        }
        // With multiple results, operations are limied
        $disp_mode = 'nnnn000000';
        $is_limited_display = true;
        // Collect the tables
        $table_html .= $displayResultsObject->getTable($result, $disp_mode, $analyzed_sql, $is_limited_display);
        // Free the result to save the memory
        PMA_DBI_free_result($result);
        $sql_no++;
    } while (PMA_DBI_more_results() && PMA_DBI_next_result());
    return $table_html;
}
Пример #4
0
/**
 * Outputs the content of a table in CSV format
 *
 * @param   string      the database name
 * @param   string      the table name
 * @param   string      the end of line sequence
 * @param   string      the url to go back in case of error
 * @param   string      SQL query for obtaining data
 *
 * @return  bool        Whether it suceeded
 *
 * @access  public
 */
function PMA_exportData($db, $table, $crlf, $error_url, $sql_query) {
    global $what;

    // Gets the data from the database
    $result      = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
    $fields_cnt  = PMA_DBI_num_fields($result);

    // If required, get fields name at the first line
    if (isset($GLOBALS[$what . '_columns'])) {
        $schema_insert = '<tr>';
        for ($i = 0; $i < $fields_cnt; $i++) {
            $schema_insert .= '<td class=xl2216681 nowrap><b>' . htmlspecialchars(stripslashes(PMA_DBI_field_name($result, $i))) . '</b></td>';
        } // end for
        $schema_insert .= '</tr>';
        if (!PMA_exportOutputHandler($schema_insert)) {
            return FALSE;
        }
    } // end if

    $fields_meta = PMA_DBI_get_fields_meta($result);

    // Format the data
    while ($row = PMA_DBI_fetch_row($result)) {
        $schema_insert = '<tr>';
        for ($j = 0; $j < $fields_cnt; $j++) {
            if (!isset($row[$j]) || is_null($row[$j])) {
                $value = $GLOBALS[$what . '_null'];
            } elseif ($row[$j] == '0' || $row[$j] != '') {
                $value = $row[$j];
            } else {
                $value = '';
            }
            $schema_insert .= '<td class=xl2216681 nowrap';
            if ('1' == $fields_meta[$j]->numeric) {
                $schema_insert .= ' x:num ';
            }
            $schema_insert .= '>' . htmlspecialchars($value) . '</td>';
        } // end for
        $schema_insert .= '</tr>';
        if (!PMA_exportOutputHandler($schema_insert)) {
            return FALSE;
        }
    } // end while
    PMA_DBI_free_result($result);

    return TRUE;
}
Пример #5
0
/**
 * Handles requests for executing a routine
 *
 * @return Does not return
 */
function PMA_RTN_handleExecute()
{
    global $_GET, $_POST, $_REQUEST, $GLOBALS, $db;
    /**
     * Handle all user requests other than the default of listing routines
     */
    if (!empty($_REQUEST['execute_routine']) && !empty($_REQUEST['item_name'])) {
        // Build the queries
        $routine = PMA_RTN_getDataFromName($_REQUEST['item_name'], $_REQUEST['item_type'], false);
        if ($routine !== false) {
            $queries = array();
            $end_query = array();
            $args = array();
            $all_functions = $GLOBALS['PMA_Types']->getAllFunctions();
            for ($i = 0; $i < $routine['item_num_params']; $i++) {
                if (isset($_REQUEST['params'][$routine['item_param_name'][$i]])) {
                    $value = $_REQUEST['params'][$routine['item_param_name'][$i]];
                    if (is_array($value)) {
                        // is SET type
                        $value = implode(',', $value);
                    }
                    $value = PMA_Util::sqlAddSlashes($value);
                    if (!empty($_REQUEST['funcs'][$routine['item_param_name'][$i]]) && in_array($_REQUEST['funcs'][$routine['item_param_name'][$i]], $all_functions)) {
                        $queries[] = "SET @p{$i}={$_REQUEST['funcs'][$routine['item_param_name'][$i]]}('{$value}');\n";
                    } else {
                        $queries[] = "SET @p{$i}='{$value}';\n";
                    }
                    $args[] = "@p{$i}";
                } else {
                    $args[] = "@p{$i}";
                }
                if ($routine['item_type'] == 'PROCEDURE') {
                    if ($routine['item_param_dir'][$i] == 'OUT' || $routine['item_param_dir'][$i] == 'INOUT') {
                        $end_query[] = "@p{$i} AS " . PMA_Util::backquote($routine['item_param_name'][$i]);
                    }
                }
            }
            if ($routine['item_type'] == 'PROCEDURE') {
                $queries[] = "CALL " . PMA_Util::backquote($routine['item_name']) . "(" . implode(', ', $args) . ");\n";
                if (count($end_query)) {
                    $queries[] = "SELECT " . implode(', ', $end_query) . ";\n";
                }
            } else {
                $queries[] = "SELECT " . PMA_Util::backquote($routine['item_name']) . "(" . implode(', ', $args) . ") " . "AS " . PMA_Util::backquote($routine['item_name']) . ";\n";
            }
            // Get all the queries as one SQL statement
            $multiple_query = implode("", $queries);
            $outcome = true;
            $affected = 0;
            // Execute query
            if (!PMA_DBI_try_multi_query($multiple_query)) {
                $outcome = false;
            }
            // Generate output
            if ($outcome) {
                // Pass the SQL queries through the "pretty printer"
                $output = '<code class="sql" style="margin-bottom: 1em;">';
                $output .= PMA_SQP_formatHtml(PMA_SQP_parse(implode($queries)));
                $output .= '</code>';
                // Display results
                $output .= "<fieldset><legend>";
                $output .= sprintf(__('Execution results of routine %s'), PMA_Util::backquote(htmlspecialchars($routine['item_name'])));
                $output .= "</legend>";
                $num_of_rusults_set_to_display = 0;
                do {
                    $result = PMA_DBI_store_result();
                    $num_rows = PMA_DBI_num_rows($result);
                    if ($result !== false && $num_rows > 0) {
                        $output .= "<table><tr>";
                        foreach (PMA_DBI_get_fields_meta($result) as $key => $field) {
                            $output .= "<th>";
                            $output .= htmlspecialchars($field->name);
                            $output .= "</th>";
                        }
                        $output .= "</tr>";
                        $color_class = 'odd';
                        while ($row = PMA_DBI_fetch_assoc($result)) {
                            $output .= "<tr>";
                            foreach ($row as $key => $value) {
                                if ($value === null) {
                                    $value = '<i>NULL</i>';
                                } else {
                                    $value = htmlspecialchars($value);
                                }
                                $output .= "<td class='" . $color_class . "'>" . $value . "</td>";
                            }
                            $output .= "</tr>";
                            $color_class = $color_class == 'odd' ? 'even' : 'odd';
                        }
                        $output .= "</table>";
                        $num_of_rusults_set_to_display++;
                        $affected = $num_rows;
                    }
                    if (!PMA_DBI_more_results()) {
                        break;
                    }
                    $output .= "<br/>";
                    PMA_DBI_free_result($result);
                } while (PMA_DBI_next_result());
                $output .= "</fieldset>";
                $message = __('Your SQL query has been executed successfully');
                if ($routine['item_type'] == 'PROCEDURE') {
                    $message .= '<br />';
                    // TODO : message need to be modified according to the
                    // output from the routine
                    $message .= sprintf(_ngettext('%d row affected by the last statement inside the procedure', '%d rows affected by the last statement inside the procedure', $affected), $affected);
                }
                $message = PMA_message::success($message);
                if ($num_of_rusults_set_to_display == 0) {
                    $notice = __('MySQL returned an empty result set (i.e. zero rows).');
                    $output .= PMA_message::notice($notice)->getDisplay();
                }
            } else {
                $output = '';
                $message = PMA_message::error(sprintf(__('The following query has failed: "%s"'), htmlspecialchars($query)) . '<br /><br />' . __('MySQL said: ') . PMA_DBI_getError(null));
            }
            // Print/send output
            if ($GLOBALS['is_ajax_request']) {
                $response = PMA_Response::getInstance();
                $response->isSuccess($message->isSuccess());
                $response->addJSON('message', $message->getDisplay() . $output);
                $response->addJSON('dialog', false);
                exit;
            } else {
                echo $message->getDisplay() . $output;
                if ($message->isError()) {
                    // At least one query has failed, so shouldn't
                    // execute any more queries, so we quit.
                    exit;
                }
                unset($_POST);
                // Now deliberately fall through to displaying the routines list
            }
        } else {
            $message = __('Error in processing request') . ' : ';
            $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_Util::backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_Util::backquote($db)));
            $message = PMA_message::error($message);
            if ($GLOBALS['is_ajax_request']) {
                $response = PMA_Response::getInstance();
                $response->isSuccess(false);
                $response->addJSON('message', $message);
                exit;
            } else {
                echo $message->getDisplay();
                unset($_POST);
            }
        }
    } else {
        if (!empty($_GET['execute_dialog']) && !empty($_GET['item_name'])) {
            /**
             * Display the execute form for a routine.
             */
            $routine = PMA_RTN_getDataFromName($_GET['item_name'], $_GET['item_type'], true);
            if ($routine !== false) {
                $form = PMA_RTN_getExecuteForm($routine);
                if ($GLOBALS['is_ajax_request'] == true) {
                    $title = __("Execute routine") . " " . PMA_Util::backquote(htmlentities($_GET['item_name'], ENT_QUOTES));
                    $response = PMA_Response::getInstance();
                    $response->addJSON('message', $form);
                    $response->addJSON('title', $title);
                    $response->addJSON('dialog', true);
                } else {
                    echo "\n\n<h2>" . __("Execute routine") . "</h2>\n\n";
                    echo $form;
                }
                exit;
            } else {
                if ($GLOBALS['is_ajax_request'] == true) {
                    $message = __('Error in processing request') . ' : ';
                    $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_Util::backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_Util::backquote($db)));
                    $message = PMA_message::error($message);
                    $response = PMA_Response::getInstance();
                    $response->isSuccess(false);
                    $response->addJSON('message', $message);
                    exit;
                }
            }
        }
    }
}
Пример #6
0
    $goto = 'tbl_change.php?' . PMA_generate_common_url($db, $table, '&') . '&goto=' . urlencode($goto) . '&pos=' . $pos . '&session_max_rows=' . $session_max_rows . '&disp_direction=' . $disp_direction . '&repeat_cells=' . $repeat_cells . '&dontlimitchars=' . $dontlimitchars . '&after_insert=' . $after_insert . (empty($sql_query) ? '' : '&sql_query=' . urlencode($sql_query));
} elseif (isset($after_insert) && $after_insert == 'same_insert') {
    $goto = 'tbl_change.php?' . PMA_generate_common_url($db, $table, '&') . '&goto=' . urlencode($goto) . '&pos=' . $pos . '&session_max_rows=' . $session_max_rows . '&disp_direction=' . $disp_direction . '&repeat_cells=' . $repeat_cells . '&dontlimitchars=' . $dontlimitchars . '&after_insert=' . $after_insert . (empty($sql_query) ? '' : '&sql_query=' . urlencode($sql_query));
    if (isset($primary_key)) {
        foreach ($primary_key as $pk) {
            $goto .= '&primary_key[]=' . $pk;
        }
    }
} elseif (isset($after_insert) && $after_insert == 'edit_next') {
    $goto = 'tbl_change.php?' . PMA_generate_common_url($db, $table, '&') . '&goto=' . urlencode($goto) . '&pos=' . $pos . '&session_max_rows=' . $session_max_rows . '&disp_direction=' . $disp_direction . '&repeat_cells=' . $repeat_cells . '&dontlimitchars=' . $dontlimitchars . '&after_insert=' . $after_insert . (empty($sql_query) ? '' : '&sql_query=' . urlencode($sql_query));
    if (isset($primary_key)) {
        foreach ($primary_key as $pk) {
            $local_query = 'SELECT * FROM ' . PMA_backquote($table) . ' WHERE ' . str_replace('` =', '` >', urldecode($pk)) . ' LIMIT 1;';
            $res = PMA_DBI_query($local_query);
            $row = PMA_DBI_fetch_row($res);
            $meta = PMA_DBI_get_fields_meta($res);
            $goto .= '&primary_key[]=' . urlencode(PMA_getUvaCondition($res, count($row), $meta, $row));
        }
    }
} elseif ($goto == 'sql.php') {
    $goto = 'sql.php?' . PMA_generate_common_url($db, $table, '&') . '&pos=' . $pos . '&session_max_rows=' . $session_max_rows . '&disp_direction=' . $disp_direction . '&repeat_cells=' . $repeat_cells . '&dontlimitchars=' . $dontlimitchars . '&sql_query=' . urlencode($sql_query);
} elseif (!empty($goto)) {
    // Security checkings
    $is_gotofile = preg_replace('@^([^?]+).*$@', '\\1', $goto);
    if (!@file_exists('./' . $is_gotofile)) {
        $goto = !isset($table) || !strlen($table) ? 'db_details.php' : 'tbl_properties.php';
        $is_gotofile = TRUE;
    } else {
        $is_gotofile = $is_gotofile == $goto;
    }
}
Пример #7
0
/**
 * Handles requests for executing a routine
 */
function PMA_RTN_handleExecute()
{
    global $_GET, $_POST, $_REQUEST, $GLOBALS, $db, $cfg;
    /**
     * Handle all user requests other than the default of listing routines
     */
    if (!empty($_REQUEST['execute_routine']) && !empty($_REQUEST['item_name'])) {
        // Build the queries
        $routine = PMA_RTN_getDataFromName($_REQUEST['item_name'], $_REQUEST['item_type'], false);
        if ($routine !== false) {
            $queries = array();
            $end_query = array();
            $args = array();
            for ($i = 0; $i < $routine['item_num_params']; $i++) {
                if (isset($_REQUEST['params'][$routine['item_param_name'][$i]])) {
                    $value = $_REQUEST['params'][$routine['item_param_name'][$i]];
                    if (is_array($value)) {
                        // is SET type
                        $value = implode(',', $value);
                    }
                    $value = PMA_sqlAddSlashes($value);
                    if (!empty($_REQUEST['funcs'][$routine['item_param_name'][$i]]) && in_array($_REQUEST['funcs'][$routine['item_param_name'][$i]], $cfg['Functions'])) {
                        $queries[] = "SET @p{$i}={$_REQUEST['funcs'][$routine['item_param_name'][$i]]}('{$value}');\n";
                    } else {
                        $queries[] = "SET @p{$i}='{$value}';\n";
                    }
                    $args[] = "@p{$i}";
                } else {
                    $args[] = "@p{$i}";
                }
                if ($routine['item_type'] == 'PROCEDURE') {
                    if ($routine['item_param_dir'][$i] == 'OUT' || $routine['item_param_dir'][$i] == 'INOUT') {
                        $end_query[] = "@p{$i} AS " . PMA_backquote($routine['item_param_name'][$i]);
                    }
                }
            }
            if ($routine['item_type'] == 'PROCEDURE') {
                $queries[] = "CALL " . PMA_backquote($routine['item_name']) . "(" . implode(', ', $args) . ");\n";
                if (count($end_query)) {
                    $queries[] = "SELECT " . implode(', ', $end_query) . ";\n";
                }
            } else {
                $queries[] = "SELECT " . PMA_backquote($routine['item_name']) . "(" . implode(', ', $args) . ") " . "AS " . PMA_backquote($routine['item_name']) . ";\n";
            }
            // Execute the queries
            $affected = 0;
            $result = null;
            $outcome = true;
            foreach ($queries as $query) {
                $resource = PMA_DBI_try_query($query);
                if ($resource === false) {
                    $outcome = false;
                    break;
                }
                while (true) {
                    if (!PMA_DBI_more_results()) {
                        break;
                    }
                    PMA_DBI_next_result();
                }
                if (substr($query, 0, 6) == 'SELECT') {
                    $result = $resource;
                } else {
                    if (substr($query, 0, 4) == 'CALL') {
                        $result = $resource ? $resource : $result;
                        $affected = PMA_DBI_affected_rows() - PMA_DBI_num_rows($resource);
                    }
                }
            }
            // Generate output
            if ($outcome) {
                $message = __('Your SQL query has been executed successfully');
                if ($routine['item_type'] == 'PROCEDURE') {
                    $message .= '<br />';
                    $message .= sprintf(_ngettext('%d row affected by the last statement inside the procedure', '%d rows affected by the last statement inside the procedure', $affected), $affected);
                }
                $message = PMA_message::success($message);
                // Pass the SQL queries through the "pretty printer"
                $output = '<code class="sql" style="margin-bottom: 1em;">';
                $output .= PMA_SQP_formatHtml(PMA_SQP_parse(implode($queries)));
                $output .= '</code>';
                // Display results
                if ($result) {
                    $output .= "<fieldset><legend>";
                    $output .= sprintf(__('Execution results of routine %s'), PMA_backquote(htmlspecialchars($routine['item_name'])));
                    $output .= "</legend>";
                    $output .= "<table><tr>";
                    foreach (PMA_DBI_get_fields_meta($result) as $key => $field) {
                        $output .= "<th>";
                        $output .= htmlspecialchars($field->name);
                        $output .= "</th>";
                    }
                    $output .= "</tr>";
                    // Stored routines can only ever return ONE ROW.
                    $data = PMA_DBI_fetch_single_row($result);
                    foreach ($data as $key => $value) {
                        if ($value === null) {
                            $value = '<i>NULL</i>';
                        } else {
                            $value = htmlspecialchars($value);
                        }
                        $output .= "<td class='odd'>" . $value . "</td>";
                    }
                    $output .= "</table></fieldset>";
                } else {
                    $notice = __('MySQL returned an empty result set (i.e. zero rows).');
                    $output .= PMA_message::notice($notice)->getDisplay();
                }
            } else {
                $output = '';
                $message = PMA_message::error(sprintf(__('The following query has failed: "%s"'), $query) . '<br /><br />' . __('MySQL said: ') . PMA_DBI_getError(null));
            }
            // Print/send output
            if ($GLOBALS['is_ajax_request']) {
                $extra_data = array('dialog' => false);
                PMA_ajaxResponse($message->getDisplay() . $output, $message->isSuccess(), $extra_data);
            } else {
                echo $message->getDisplay() . $output;
                if ($message->isError()) {
                    // At least one query has failed, so shouldn't
                    // execute any more queries, so we quit.
                    exit;
                }
                unset($_POST);
                // Now deliberately fall through to displaying the routines list
            }
        } else {
            $message = __('Error in processing request') . ' : ';
            $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_backquote($db)));
            $message = PMA_message::error($message);
            if ($GLOBALS['is_ajax_request']) {
                PMA_ajaxResponse($message, $message->isSuccess());
            } else {
                echo $message->getDisplay();
                unset($_POST);
            }
        }
    } else {
        if (!empty($_GET['execute_dialog']) && !empty($_GET['item_name'])) {
            /**
             * Display the execute form for a routine.
             */
            $routine = PMA_RTN_getDataFromName($_GET['item_name'], $_GET['item_type'], true);
            if ($routine !== false) {
                $form = PMA_RTN_getExecuteForm($routine);
                if ($GLOBALS['is_ajax_request'] == true) {
                    $extra_data = array();
                    $extra_data['dialog'] = true;
                    $extra_data['title'] = __("Execute routine") . " ";
                    $extra_data['title'] .= PMA_backquote(htmlentities($_GET['item_name'], ENT_QUOTES));
                    PMA_ajaxResponse($form, true, $extra_data);
                } else {
                    echo "\n\n<h2>" . __("Execute routine") . "</h2>\n\n";
                    echo $form;
                    include './libraries/footer.inc.php';
                    // exit;
                }
            } else {
                if ($GLOBALS['is_ajax_request'] == true) {
                    $message = __('Error in processing request') . ' : ';
                    $message .= sprintf(PMA_RTE_getWord('not_found'), htmlspecialchars(PMA_backquote($_REQUEST['item_name'])), htmlspecialchars(PMA_backquote($db)));
                    $message = PMA_message::error($message);
                    PMA_ajaxResponse($message, false);
                }
            }
        }
    }
}
Пример #8
0
/**
 * returns $type array of rows from given $result
 *
 * The following function is meant for internal use only.
 * Do not call it from outside this library!
 *
 * @uses    $GLOBALS['allow_recoding']
 * @uses    $GLOBALS['cfg']['AllowAnywhereRecoding']
 * @uses    PMA_MYSQL_INT_VERSION
 * @uses    PMA_DBI_get_fields_meta()
 * @uses    PMA_convert_display_charset()
 * @uses    mysqli_fetch_array()
 * @uses    mysqli_num_fields()
 * @uses    stristr()
 * @param   object mysqli result    $result
 * @param   integer                 $type   ASSOC, BOTH, or NUMERIC array
 * @return  array                   results
 * @access  protected
 */
function PMA_mysqli_fetch_array($result, $type = false)
{
    if ($type != false) {
        $data = @mysqli_fetch_array($result, $type);
    } else {
        $data = @mysqli_fetch_array($result);
    }
    /* No data returned => do not touch it */
    if (!$data) {
        return $data;
    }
    if (!defined('PMA_MYSQL_INT_VERSION') || PMA_MYSQL_INT_VERSION >= 40100 || !(isset($GLOBALS['cfg']['AllowAnywhereRecoding']) && $GLOBALS['cfg']['AllowAnywhereRecoding'] && $GLOBALS['allow_recoding'])) {
        /* No recoding -> return data as we got them */
        return $data;
    }
    $ret = array();
    $num = mysqli_num_fields($result);
    if ($num > 0) {
        $fields = PMA_DBI_get_fields_meta($result);
    }
    // sometimes, mysqli_fetch_fields() does not return results
    // (as seen in PHP 5.1.0-dev), so for now, return $data unchanged
    if (!$fields) {
        return $data;
    }
    $i = 0;
    for ($i = 0; $i < $num; $i++) {
        if (!isset($fields[$i]->type)) {
            /* No meta information available -> we guess that it should be
             * converted */
            if (isset($data[$i])) {
                $ret[$i] = PMA_convert_display_charset($data[$i]);
            }
            if (isset($fields[$i]->name) && isset($data[$fields[$i]->name])) {
                $ret[PMA_convert_display_charset($fields[$i]->name)] = PMA_convert_display_charset($data[$fields[$i]->name]);
            }
        } else {
            /* Meta information available -> check type of field and convert
             * it according to the type */
            if (stristr($fields[$i]->type, 'BLOB') || stristr($fields[$i]->type, 'BINARY')) {
                if (isset($data[$i])) {
                    $ret[$i] = $data[$i];
                }
                if (isset($data[$fields[$i]->name])) {
                    $ret[PMA_convert_display_charset($fields[$i]->name)] = $data[$fields[$i]->name];
                }
            } else {
                if (isset($data[$i])) {
                    $ret[$i] = PMA_convert_display_charset($data[$i]);
                }
                if (isset($data[$fields[$i]->name])) {
                    $ret[PMA_convert_display_charset($fields[$i]->name)] = PMA_convert_display_charset($data[$fields[$i]->name]);
                }
            }
        }
    }
    return $ret;
}
if (!$is_backup) {
    $header_cells[] = __('Index');
}
$header_cells[] = '<abbr title="AUTO_INCREMENT">A_I</abbr>';
require_once './libraries/transformations.lib.php';
$cfgRelation = PMA_getRelationsParam();
$comments_map = array();
$mime_map = array();
$available_mime = array();
$comments_map = PMA_getComments($db, $table);
$header_cells[] = __('Comments');
if (isset($fields_meta)) {
    // for moving, load all available column names
    $move_columns_sql_query = 'SELECT * FROM ' . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table) . ' LIMIT 1';
    $move_columns_sql_result = PMA_DBI_try_query($move_columns_sql_query);
    $move_columns = PMA_DBI_get_fields_meta($move_columns_sql_result);
    unset($move_columns_sql_query, $move_columns_sql_result);
    $header_cells[] = __('Move column');
}
if ($cfgRelation['mimework'] && $GLOBALS['cfg']['BrowseMIME']) {
    $mime_map = PMA_getMIME($db, $table);
    $available_mime = PMA_getAvailableMIMEtypes();
    $hint = '<br />' . sprintf(__('For a list of available transformation options and their MIME' . ' type transformations, click on %stransformation descriptions%s'), '<a href="transformation_overview.php?' . PMA_generate_common_url($db, $table) . '" target="_blank">', '</a>');
    $header_cells[] = __('MIME type');
    $header_cells[] = __('Browser transformation');
    $header_cells[] = __('Transformation options') . PMA_Util::showHint(__('Please enter the values for transformation options using this' . ' format: \'a\', 100, b,\'c\'…<br />If you ever need to put' . ' a backslash ("\\") or a single quote ("\'") amongst those' . ' values, precede it with a backslash (for example \'\\\\xyz\'' . ' or \'a\\\'b\').') . $hint);
}
//  workaround for field_fulltext, because its submitted indices contain
//  the index as a value, not a key. Inserted here for easier maintaineance
//  and less code to change in existing files.
if (isset($field_fulltext) && is_array($field_fulltext)) {
Пример #10
0
function PMA_mysqli_fetch_array($result, $type = FALSE)
{
    global $cfg, $allow_recoding, $charset, $convcharset;
    if ($type != FALSE) {
        $data = @mysqli_fetch_array($result, $type);
    } else {
        $data = @mysqli_fetch_array($result);
    }
    /* No data returned => do not touch it */
    if (!$data) {
        return $data;
    }
    if (!defined('PMA_MYSQL_INT_VERSION') || PMA_MYSQL_INT_VERSION >= 40100 || !(isset($cfg['AllowAnywhereRecoding']) && $cfg['AllowAnywhereRecoding'] && $allow_recoding)) {
        /* No recoding -> return data as we got them */
        return $data;
    } else {
        $ret = array();
        $num = mysqli_num_fields($result);
        if ($num > 0) {
            $fields = PMA_DBI_get_fields_meta($result);
        }
        $i = 0;
        for ($i = 0; $i < $num; $i++) {
            if (!isset($fields[$i]->type)) {
                /* No meta information available -> we guess that it should be converted */
                if (isset($data[$i])) {
                    $ret[$i] = PMA_convert_display_charset($data[$i]);
                }
                if (isset($fields[$i]->name) && isset($data[$fields[$i]->name])) {
                    $ret[PMA_convert_display_charset($fields[$i]->name)] = PMA_convert_display_charset($data[$fields[$i]->name]);
                }
            } else {
                /* Meta information available -> check type of field and convert it according to the type */
                if (stristr($fields[$i]->type, 'BLOB') || stristr($fields[$i]->type, 'BINARY')) {
                    if (isset($data[$i])) {
                        $ret[$i] = $data[$i];
                    }
                    if (isset($data[$fields[$i]->name])) {
                        $ret[PMA_convert_display_charset($fields[$i]->name)] = $data[$fields[$i]->name];
                    }
                } else {
                    if (isset($data[$i])) {
                        $ret[$i] = PMA_convert_display_charset($data[$i]);
                    }
                    if (isset($data[$fields[$i]->name])) {
                        $ret[PMA_convert_display_charset($fields[$i]->name)] = PMA_convert_display_charset($data[$fields[$i]->name]);
                    }
                }
            }
        }
        return $ret;
    }
}
Пример #11
0
 /**
  * Outputs the content of a table in CSV format
  *
  * @param   string      the database name
  * @param   string      the table name
  * @param   string      the end of line sequence
  * @param   string      the url to go back in case of error
  * @param   string      SQL query for obtaining data
  *
  * @return  bool        Whether it suceeded
  *
  * @access  public
  */
 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
 {
     global $what;
     // Gets the data from the database
     $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
     $fields_cnt = PMA_DBI_num_fields($result);
     $fields_meta = PMA_DBI_get_fields_meta($result);
     $field_flags = array();
     for ($j = 0; $j < $fields_cnt; $j++) {
         $field_flags[$j] = PMA_DBI_field_flags($result, $j);
     }
     $GLOBALS['ods_buffer'] .= '<table:table table:name="' . htmlspecialchars($table) . '">';
     // If required, get fields name at the first line
     if (isset($GLOBALS[$what . '_columns'])) {
         $GLOBALS['ods_buffer'] .= '<table:table-row>';
         for ($i = 0; $i < $fields_cnt; $i++) {
             $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars(stripslashes(PMA_DBI_field_name($result, $i))) . '</text:p>' . '</table:table-cell>';
         }
         // end for
         $GLOBALS['ods_buffer'] .= '</table:table-row>';
     }
     // end if
     // Format the data
     while ($row = PMA_DBI_fetch_row($result)) {
         $GLOBALS['ods_buffer'] .= '<table:table-row>';
         for ($j = 0; $j < $fields_cnt; $j++) {
             if (!isset($row[$j]) || is_null($row[$j])) {
                 $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($GLOBALS[$what . '_null']) . '</text:p>' . '</table:table-cell>';
                 // ignore binary field
                 // Note: with mysqli, under MySQL 4.1.3, we get the flag
                 // "binary" for those field types (I don't know why)
             } elseif (stristr($field_flags[$j], 'BINARY') && isset($GLOBALS['sql_hex_for_binary']) && $fields_meta[$j]->type != 'datetime' && $fields_meta[$j]->type != 'date' && $fields_meta[$j]->type != 'time' && $fields_meta[$j]->type != 'timestamp') {
                 $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p></text:p>' . '</table:table-cell>';
             } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp' && !$fields_meta[$j]->blob) {
                 $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="float" office:value="' . $row[$j] . '" >' . '<text:p>' . htmlspecialchars($row[$j]) . '</text:p>' . '</table:table-cell>';
             } else {
                 $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($row[$j]) . '</text:p>' . '</table:table-cell>';
             }
         }
         // end for
         $GLOBALS['ods_buffer'] .= '</table:table-row>';
     }
     // end while
     PMA_DBI_free_result($result);
     $GLOBALS['ods_buffer'] .= '</table:table>';
     return TRUE;
 }
Пример #12
0
    $result = array();
    $found_unique_key = false;
    foreach ($primary_key_array as $rowcount => $primary_key) {
        $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . ' WHERE ' . $primary_key . ';';
        $result[$rowcount] = PMA_DBI_query($local_query, null, PMA_DBI_QUERY_STORE);
        $row[$rowcount] = PMA_DBI_fetch_assoc($result[$rowcount]);
        $primary_keys[$rowcount] = str_replace('\\', '\\\\', $primary_key);
        // No row returned
        if (!$row[$rowcount]) {
            unset($row[$rowcount], $primary_key_array[$rowcount]);
            PMA_showMessage($strEmptyResultSet, $local_query);
            echo "\n";
            require_once './libraries/footer.inc.php';
        } else {
            // end if (no record returned)
            $meta = PMA_DBI_get_fields_meta($result[$rowcount]);
            if ($tmp = PMA_getUniqueCondition($result[$rowcount], count($meta), $meta, $row[$rowcount], true)) {
                $found_unique_key = true;
            }
            unset($tmp);
        }
    }
} else {
    $result = PMA_DBI_query('SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . ' LIMIT 1;', null, PMA_DBI_QUERY_STORE);
    unset($row);
}
// <*****@*****.**>
// retrieve keys into foreign fields, if any
$cfgRelation = PMA_getRelationsParam();
$foreigners = $cfgRelation['relwork'] ? PMA_getForeigners($db, $table) : FALSE;
/**
Пример #13
0
 function mysql_report($query, $attr = array())
 {
     foreach ($attr as $key => $val) {
         $this->{$key} = $val;
     }
     // Pass 1 for column widths
     // TODO: force here a LIMIT to speed up pass 1 ?
     $this->results = PMA_DBI_query($query, null, PMA_DBI_QUERY_UNBUFFERED);
     $this->numFields = PMA_DBI_num_fields($this->results);
     $this->fields = PMA_DBI_get_fields_meta($this->results);
     // if column widths not set
     if (!isset($this->tablewidths)) {
         // starting col width
         $this->sColWidth = ($this->w - $this->lMargin - $this->rMargin) / $this->numFields;
         // loop through results header and set initial col widths/ titles/ alignment
         // if a col title is less than the starting col width / reduce that column size
         for ($i = 0; $i < $this->numFields; $i++) {
             $stringWidth = $this->getstringwidth($this->fields[$i]->name) + 6;
             // set any column titles less than the start width to the column title width
             if ($stringWidth < $this->sColWidth) {
                 $colFits[$i] = $stringWidth;
             }
             $this->colTitles[$i] = $this->fields[$i]->name;
             $this->display_column[$i] = true;
             switch ($this->fields[$i]->type) {
                 case 'int':
                     $this->colAlign[$i] = 'R';
                     break;
                 case 'blob':
                 case 'tinyblob':
                 case 'mediumblob':
                 case 'longblob':
                     //TODO: do not deactivate completely the display
                     // but show the field's name and [BLOB]
                     if (stristr($this->fields[$i]->flags, 'BINARY')) {
                         $this->display_column[$i] = false;
                         unset($this->colTitles[$i]);
                     }
                     $this->colAlign[$i] = 'L';
                     break;
                 default:
                     $this->colAlign[$i] = 'L';
             }
         }
         // loop through the data, any column whose contents is bigger
         // than the col size is resized
         // TODO: force here a LIMIT to avoid reading all rows
         while ($row = PMA_DBI_fetch_row($this->results)) {
             foreach ($colFits as $key => $val) {
                 $stringWidth = $this->getstringwidth($row[$key]) + 6;
                 if ($stringWidth > $this->sColWidth) {
                     // any col where row is bigger than the start width is now discarded
                     unset($colFits[$key]);
                 } else {
                     // if text is not bigger than the current column width setting enlarge the column
                     if ($stringWidth > $val) {
                         $colFits[$key] = $stringWidth;
                     }
                 }
             }
         }
         $totAlreadyFitted = 0;
         foreach ($colFits as $key => $val) {
             // set fitted columns to smallest size
             $this->tablewidths[$key] = $val;
             // to work out how much (if any) space has been freed up
             $totAlreadyFitted += $val;
         }
         $surplus = sizeof($colFits) * $this->sColWidth - $totAlreadyFitted;
         for ($i = 0; $i < $this->numFields; $i++) {
             if (!in_array($i, array_keys($colFits))) {
                 $this->tablewidths[$i] = $this->sColWidth + $surplus / ($this->numFields - sizeof($colFits));
             }
             if ($this->display_column[$i] == false) {
                 $this->tablewidths[$i] = 0;
             }
         }
         ksort($this->tablewidths);
     }
     PMA_DBI_free_result($this->results);
     // Pass 2
     $this->results = PMA_DBI_query($query, null, PMA_DBI_QUERY_UNBUFFERED);
     $this->Open();
     $this->setY($this->tMargin);
     $this->AddPage();
     $this->morepagestable($this->FontSizePt);
     PMA_DBI_free_result($this->results);
 }
Пример #14
0
/**
 * set $_SESSION for edit_next
 *
 * @param string $one_where_clause one where clause from where clauses array
 *
 * @return void
 */
function PMA_setSessionForEditNext($one_where_clause)
{
    $local_query = 'SELECT * FROM ' . PMA_Util::backquote($GLOBALS['db']) . '.' . PMA_Util::backquote($GLOBALS['table']) . ' WHERE ' . str_replace('` =', '` >', $one_where_clause) . ' LIMIT 1;';
    $res = PMA_DBI_query($local_query);
    $row = PMA_DBI_fetch_row($res);
    $meta = PMA_DBI_get_fields_meta($res);
    // must find a unique condition based on unique key,
    // not a combination of all fields
    list($unique_condition, $clause_is_unique) = PMA_Util::getUniqueCondition($res, count($meta), $meta, $row, true);
    if (!empty($unique_condition)) {
        $_SESSION['edit_next'] = $unique_condition;
    }
    unset($unique_condition, $clause_is_unique);
}
Пример #15
0
 /**
  * Outputs the content of a table in ODS format
  *
  * @param string  $db         database name
  * @param string  $table      table name
  * @param string  $crlf       the end of line sequence
  * @param string  $error_url  the url to go back in case of error
  * @param string  $sql_query  SQL query for obtaining data
  * @return  bool        Whether it succeeded
  *
  * @access  public
  */
 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
 {
     global $what;
     // Gets the data from the database
     $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
     $fields_cnt = PMA_DBI_num_fields($result);
     $fields_meta = PMA_DBI_get_fields_meta($result);
     $field_flags = array();
     for ($j = 0; $j < $fields_cnt; $j++) {
         $field_flags[$j] = PMA_DBI_field_flags($result, $j);
     }
     $GLOBALS['ods_buffer'] .= '<table:table table:name="' . htmlspecialchars($table) . '">';
     // If required, get fields name at the first line
     if (isset($GLOBALS[$what . '_columns'])) {
         $GLOBALS['ods_buffer'] .= '<table:table-row>';
         for ($i = 0; $i < $fields_cnt; $i++) {
             $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars(stripslashes(PMA_DBI_field_name($result, $i))) . '</text:p>' . '</table:table-cell>';
         }
         // end for
         $GLOBALS['ods_buffer'] .= '</table:table-row>';
     }
     // end if
     // Format the data
     while ($row = PMA_DBI_fetch_row($result)) {
         $GLOBALS['ods_buffer'] .= '<table:table-row>';
         for ($j = 0; $j < $fields_cnt; $j++) {
             if (!isset($row[$j]) || is_null($row[$j])) {
                 $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($GLOBALS[$what . '_null']) . '</text:p>' . '</table:table-cell>';
                 // ignore BLOB
             } elseif (stristr($field_flags[$j], 'BINARY') && $fields_meta[$j]->blob) {
                 $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p></text:p>' . '</table:table-cell>';
             } elseif ($fields_meta[$j]->type == "date") {
                 $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="date" office:date-value="' . date("Y-m-d", strtotime($row[$j])) . '" table:style-name="DateCell">' . '<text:p>' . htmlspecialchars($row[$j]) . '</text:p>' . '</table:table-cell>';
             } elseif ($fields_meta[$j]->type == "time") {
                 $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="time" office:time-value="' . date("\\P\\TH\\Hi\\Ms\\S", strtotime($row[$j])) . '" table:style-name="TimeCell">' . '<text:p>' . htmlspecialchars($row[$j]) . '</text:p>' . '</table:table-cell>';
             } elseif ($fields_meta[$j]->type == "datetime") {
                 $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="date" office:date-value="' . date("Y-m-d\\TH:i:s", strtotime($row[$j])) . '" table:style-name="DateTimeCell">' . '<text:p>' . htmlspecialchars($row[$j]) . '</text:p>' . '</table:table-cell>';
             } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp' && !$fields_meta[$j]->blob) {
                 $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="float" office:value="' . $row[$j] . '" >' . '<text:p>' . htmlspecialchars($row[$j]) . '</text:p>' . '</table:table-cell>';
             } else {
                 $GLOBALS['ods_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($row[$j]) . '</text:p>' . '</table:table-cell>';
             }
         }
         // end for
         $GLOBALS['ods_buffer'] .= '</table:table-row>';
     }
     // end while
     PMA_DBI_free_result($result);
     $GLOBALS['ods_buffer'] .= '</table:table>';
     return true;
 }
Пример #16
0
 /**
  * Outputs the content of a table in CSV format
  *
  * @param   string      the database name
  * @param   string      the table name
  * @param   string      the end of line sequence
  * @param   string      the url to go back in case of error
  * @param   string      SQL query for obtaining data
  *
  * @return  bool        Whether it suceeded
  *
  * @access  public
  */
 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
 {
     global $what;
     // Gets the data from the database
     $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
     $fields_cnt = PMA_DBI_num_fields($result);
     $fields_meta = PMA_DBI_get_fields_meta($result);
     $field_flags = array();
     for ($j = 0; $j < $fields_cnt; $j++) {
         $field_flags[$j] = PMA_DBI_field_flags($result, $j);
     }
     $GLOBALS['odt_buffer'] .= '<text:h text:outline-level="2" text:style-name="Heading_2" text:is-list-header="true">' . htmlspecialchars(__('Dumping data for table') . ' ' . $table) . '</text:h>';
     $GLOBALS['odt_buffer'] .= '<table:table table:name="' . htmlspecialchars($table) . '_structure">';
     $GLOBALS['odt_buffer'] .= '<table:table-column table:number-columns-repeated="' . $fields_cnt . '"/>';
     // If required, get fields name at the first line
     if (isset($GLOBALS[$what . '_columns'])) {
         $GLOBALS['odt_buffer'] .= '<table:table-row>';
         for ($i = 0; $i < $fields_cnt; $i++) {
             $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars(stripslashes(PMA_DBI_field_name($result, $i))) . '</text:p>' . '</table:table-cell>';
         }
         // end for
         $GLOBALS['odt_buffer'] .= '</table:table-row>';
     }
     // end if
     // Format the data
     while ($row = PMA_DBI_fetch_row($result)) {
         $GLOBALS['odt_buffer'] .= '<table:table-row>';
         for ($j = 0; $j < $fields_cnt; $j++) {
             if (!isset($row[$j]) || is_null($row[$j])) {
                 $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($GLOBALS[$what . '_null']) . '</text:p>' . '</table:table-cell>';
                 // ignore BLOB
             } elseif (stristr($field_flags[$j], 'BINARY') && $fields_meta[$j]->blob) {
                 $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p></text:p>' . '</table:table-cell>';
             } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp' && !$fields_meta[$j]->blob) {
                 $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="float" office:value="' . $row[$j] . '" >' . '<text:p>' . htmlspecialchars($row[$j]) . '</text:p>' . '</table:table-cell>';
             } else {
                 $GLOBALS['odt_buffer'] .= '<table:table-cell office:value-type="string">' . '<text:p>' . htmlspecialchars($row[$j]) . '</text:p>' . '</table:table-cell>';
             }
         }
         // end for
         $GLOBALS['odt_buffer'] .= '</table:table-row>';
     }
     // end while
     PMA_DBI_free_result($result);
     $GLOBALS['odt_buffer'] .= '</table:table>';
     return TRUE;
 }
Пример #17
0
             require './libraries/server_common.inc.php';
             require './libraries/server_links.inc.php';
         }
     } else {
         require_once './libraries/header.inc.php';
         //we don't need to buffer the output in PMA_showMessage here.
         //set a global variable and check against it in the function
         $GLOBALS['buffer_message'] = false;
     }
 }
 if (strlen($db)) {
     $cfgRelation = PMA_getRelationsParam();
 }
 // Gets the list of fields properties
 if (isset($result) && $result) {
     $fields_meta = PMA_DBI_get_fields_meta($result, $table);
     $fields_cnt = count($fields_meta);
 }
 if (!$GLOBALS['is_ajax_request']) {
     //begin the sqlqueryresults div here. container div
     echo '<div id="sqlqueryresults"';
     if ($GLOBALS['cfg']['AjaxEnable']) {
         echo ' class="ajax"';
     }
     echo '>';
 }
 // Display previous update query (from tbl_replace)
 if (isset($disp_query) && $cfg['ShowSQL'] == true) {
     PMA_showMessage($disp_message, $disp_query, 'success');
 }
 if (isset($profiling_results)) {
Пример #18
0
 function mysql_report($query, $attr = array())
 {
     foreach ($attr as $key => $val) {
         $this->{$key} = $val;
     }
     /**
      * Pass 1 for column widths
      */
     $this->results = PMA_DBI_query($query, null, PMA_DBI_QUERY_UNBUFFERED);
     $this->numFields = PMA_DBI_num_fields($this->results);
     $this->fields = PMA_DBI_get_fields_meta($this->results);
     // if column widths not set
     if (!isset($this->tablewidths)) {
         // sColWidth = starting col width (an average size width)
         $availableWidth = $this->w - $this->lMargin - $this->rMargin;
         $this->sColWidth = $availableWidth / $this->numFields;
         $totalTitleWidth = 0;
         // loop through results header and set initial col widths/ titles/ alignment
         // if a col title is less than the starting col width, reduce that column size
         for ($i = 0; $i < $this->numFields; $i++) {
             $stringWidth = $this->getstringwidth($this->fields[$i]->name) + 6;
             // save the real title's width
             $titleWidth[$i] = $stringWidth;
             $totalTitleWidth += $stringWidth;
             // set any column titles less than the start width to the column title width
             if ($stringWidth < $this->sColWidth) {
                 $colFits[$i] = $stringWidth;
             }
             $this->colTitles[$i] = $this->fields[$i]->name;
             $this->display_column[$i] = true;
             switch ($this->fields[$i]->type) {
                 case 'int':
                     $this->colAlign[$i] = 'R';
                     break;
                 case 'blob':
                 case 'tinyblob':
                 case 'mediumblob':
                 case 'longblob':
                     /**
                      * @todo do not deactivate completely the display
                      * but show the field's name and [BLOB]
                      */
                     if (stristr($this->fields[$i]->flags, 'BINARY')) {
                         $this->display_column[$i] = false;
                         unset($this->colTitles[$i]);
                     }
                     $this->colAlign[$i] = 'L';
                     break;
                 default:
                     $this->colAlign[$i] = 'L';
             }
         }
         // title width verification
         if ($totalTitleWidth > $availableWidth) {
             $adjustingMode = true;
         } else {
             $adjustingMode = false;
             // we have enough space for all the titles at their
             // original width so use the true title's width
             foreach ($titleWidth as $key => $val) {
                 $colFits[$key] = $val;
             }
         }
         // loop through the data, any column whose contents is bigger
         // than the col size is resized
         /**
          * @todo force here a LIMIT to avoid reading all rows
          */
         while ($row = PMA_DBI_fetch_row($this->results)) {
             foreach ($colFits as $key => $val) {
                 $stringWidth = $this->getstringwidth($row[$key]) + 6;
                 if ($adjustingMode && $stringWidth > $this->sColWidth) {
                     // any column whose data's width is bigger than the start width is now discarded
                     unset($colFits[$key]);
                 } else {
                     // if data's width is bigger than the current column width,
                     // enlarge the column (but avoid enlarging it if the
                     // data's width is very big)
                     if ($stringWidth > $val && $stringWidth < $this->sColWidth * 3) {
                         $colFits[$key] = $stringWidth;
                     }
                 }
             }
         }
         $totAlreadyFitted = 0;
         foreach ($colFits as $key => $val) {
             // set fitted columns to smallest size
             $this->tablewidths[$key] = $val;
             // to work out how much (if any) space has been freed up
             $totAlreadyFitted += $val;
         }
         if ($adjustingMode) {
             $surplus = sizeof($colFits) * $this->sColWidth - $totAlreadyFitted;
             $surplusToAdd = $surplus / ($this->numFields - sizeof($colFits));
         } else {
             $surplusToAdd = 0;
         }
         for ($i = 0; $i < $this->numFields; $i++) {
             if (!in_array($i, array_keys($colFits))) {
                 $this->tablewidths[$i] = $this->sColWidth + $surplusToAdd;
             }
             if ($this->display_column[$i] == false) {
                 $this->tablewidths[$i] = 0;
             }
         }
         ksort($this->tablewidths);
     }
     PMA_DBI_free_result($this->results);
     // Pass 2
     $this->results = PMA_DBI_query($query, null, PMA_DBI_QUERY_UNBUFFERED);
     $this->Open();
     $this->setY($this->tMargin);
     $this->AddPage();
     $this->morepagestable($this->FontSizePt);
     PMA_DBI_free_result($this->results);
 }
Пример #19
0
function PMA_exportData($db, $table, $crlf, $handle)
{
    global $current_row;
    $count = 10000;
    $limit = 0;
    // We have modified this code because we were getting error if inserts were >50000
    $cnt_qry = 'SELECT count(*) FROM `' . $db . '`.`' . $table . '`';
    $cnt_res = mysql_fetch_row(mysql_query($cnt_qry));
    $sql_query = 'SELECT * FROM `' . $db . '`.`' . $table . '` LIMIT 0,10000';
    $formatted_table_name = '\'' . $table . '\'';
    $squery = mysql_query($sql_query);
    $fields_cnt = mysql_num_fields($squery);
    // Get field information
    $fields_meta = PMA_DBI_get_fields_meta($squery);
    $field_flags = array();
    for ($j = 0; $j < $fields_cnt; $j++) {
        $field_flags[$j] = mysql_field_flags($squery, $j);
    }
    for ($j = 0; $j < $fields_cnt; $j++) {
        $field_set[$j] = '`' . $fields_meta[$j]->name . '`';
    }
    $sql_command = 'INSERT';
    $insert_delayed = '';
    $separator = ',';
    $schema_insert = $sql_command . $insert_delayed . ' INTO `' . $table . '` VALUES';
    $search = array("", "\n", "\r", "");
    //\x08\\x09, not required
    $replace = array('\\0', '\\n', '\\r', '\\Z');
    $current_row = 0;
    $query_size = 0;
    $schema_insert .= $crlf;
    for ($i = $cnt_res[0]; $i >= 0; $i--) {
        // Now if 10000 rows has been processed than select next.
        if ($count == 0) {
            // Now free the result for preventing memory exhaust
            mysql_free_result($squery);
            $count = 10000;
            $limit = $limit + 10000;
            $sql_query = 'SELECT * FROM `' . $db . '`.`' . $table . '` LIMIT ' . $limit . ', 10000';
            $squery = mysql_query($sql_query);
        }
        $row = mysql_fetch_array($squery);
        // If we get empty result than break the loop
        if (!$row) {
            break;
        }
        if ($current_row == 0) {
            $head = PMA_exportComment() . PMA_exportComment('Dumping data for table' . ' ' . $formatted_table_name) . PMA_exportComment() . $crlf;
            fwrite($handle, $head);
        }
        $current_row++;
        for ($j = 0; $j < $fields_cnt; $j++) {
            // NULL
            if (!isset($row[$j]) || is_null($row[$j])) {
                $values[] = 'NULL';
                // a number
                // timestamp is numeric on some MySQL 4.1, BLOBs are sometimes numeric
            } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp' && !$fields_meta[$j]->blob) {
                $values[] = $row[$j];
            } else {
                $values[] = '\'' . str_replace($search, $replace, PMA_sqlAddslashes($row[$j])) . '\'';
            }
            // end if
        }
        // end for
        if ($current_row == 1) {
            $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
        } else {
            $insert_line = '(' . implode(', ', $values) . ')';
            if ($query_size + strlen($insert_line) > 50000) {
                $query_buffer = ';' . $crlf;
                fwrite($handle, $query_buffer);
                $query_size = 0;
                $current_row = 1;
                $insert_line = $schema_insert . $insert_line;
            }
        }
        // Gather query size
        $query_size += strlen($insert_line);
        unset($values);
        $query_buffer = ($current_row == 1 ? '' : $separator . $crlf) . $insert_line;
        // To avoide MEMORY EXHAUST
        fwrite($handle, $query_buffer);
        // Decrement till 0 so that next 10000 rows can be selected
        $count--;
    }
    // End of FOR
    if ($current_row > 0) {
        $query_buffer = ';' . $crlf;
        fwrite($handle, $query_buffer);
    }
    // Free resourses
    mysql_free_result($squery);
    $end_line = (!empty($query_buffer) ? $crlf : '') . PMA_exportComment('--------------------------------------------------------');
    fwrite($handle, $end_line);
    //return $query_buffer . $end_line;
}
Пример #20
0
 /**
  * Outputs the content of a table in SQL format
  *
  * @param string $db        database name
  * @param string $table     table name
  * @param string $crlf      the end of line sequence
  * @param string $error_url the url to go back in case of error
  * @param string $sql_query SQL query for obtaining data
  *
  * @return bool Whether it succeeded
  */
 public function exportData($db, $table, $crlf, $error_url, $sql_query)
 {
     global $current_row, $sql_backquotes;
     if (isset($GLOBALS['sql_compatibility'])) {
         $compat = $GLOBALS['sql_compatibility'];
     } else {
         $compat = 'NONE';
     }
     $formatted_table_name = isset($GLOBALS['sql_backquotes']) ? PMA_Util::backquoteCompat($table, $compat) : '\'' . $table . '\'';
     // Do not export data for a VIEW
     // (For a VIEW, this is called only when exporting a single VIEW)
     if (PMA_Table::isView($db, $table)) {
         $head = $this->_possibleCRLF() . $this->_exportComment() . $this->_exportComment('VIEW ' . ' ' . $formatted_table_name) . $this->_exportComment(__('Data') . ': ' . __('None')) . $this->_exportComment() . $this->_possibleCRLF();
         if (!PMA_exportOutputHandler($head)) {
             return false;
         }
         return true;
     }
     // analyze the query to get the true column names, not the aliases
     // (this fixes an undefined index, also if Complete inserts
     //  are used, we did not get the true column name in case of aliases)
     $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query));
     $result = PMA_DBI_try_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
     // a possible error: the table has crashed
     $tmp_error = PMA_DBI_getError();
     if ($tmp_error) {
         return PMA_exportOutputHandler($this->_exportComment(__('Error reading data:') . ' (' . $tmp_error . ')'));
     }
     if ($result != false) {
         $fields_cnt = PMA_DBI_num_fields($result);
         // Get field information
         $fields_meta = PMA_DBI_get_fields_meta($result);
         $field_flags = array();
         for ($j = 0; $j < $fields_cnt; $j++) {
             $field_flags[$j] = PMA_DBI_field_flags($result, $j);
         }
         for ($j = 0; $j < $fields_cnt; $j++) {
             if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) {
                 $field_set[$j] = PMA_Util::backquoteCompat($analyzed_sql[0]['select_expr'][$j]['column'], $compat, $sql_backquotes);
             } else {
                 $field_set[$j] = PMA_Util::backquoteCompat($fields_meta[$j]->name, $compat, $sql_backquotes);
             }
         }
         if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
             // update
             $schema_insert = 'UPDATE ';
             if (isset($GLOBALS['sql_ignore'])) {
                 $schema_insert .= 'IGNORE ';
             }
             // avoid EOL blank
             $schema_insert .= PMA_Util::backquoteCompat($table, $compat, $sql_backquotes) . ' SET';
         } else {
             // insert or replace
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'REPLACE') {
                 $sql_command = 'REPLACE';
             } else {
                 $sql_command = 'INSERT';
             }
             // delayed inserts?
             if (isset($GLOBALS['sql_delayed'])) {
                 $insert_delayed = ' DELAYED';
             } else {
                 $insert_delayed = '';
             }
             // insert ignore?
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'INSERT' && isset($GLOBALS['sql_ignore'])) {
                 $insert_delayed .= ' IGNORE';
             }
             //truncate table before insert
             if (isset($GLOBALS['sql_truncate']) && $GLOBALS['sql_truncate'] && $sql_command == 'INSERT') {
                 $truncate = 'TRUNCATE TABLE ' . PMA_Util::backquoteCompat($table, $compat, $sql_backquotes) . ";";
                 $truncatehead = $this->_possibleCRLF() . $this->_exportComment() . $this->_exportComment(__('Truncate table before insert') . ' ' . $formatted_table_name) . $this->_exportComment() . $crlf;
                 PMA_exportOutputHandler($truncatehead);
                 PMA_exportOutputHandler($truncate);
             } else {
                 $truncate = '';
             }
             // scheme for inserting fields
             if ($GLOBALS['sql_insert_syntax'] == 'complete' || $GLOBALS['sql_insert_syntax'] == 'both') {
                 $fields = implode(', ', $field_set);
                 $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_Util::backquoteCompat($table, $compat, $sql_backquotes) . ' (' . $fields . ') VALUES';
             } else {
                 $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_Util::backquoteCompat($table, $compat, $sql_backquotes) . ' VALUES';
             }
         }
         //\x08\\x09, not required
         $search = array("", "\n", "\r", "");
         $replace = array('\\0', '\\n', '\\r', '\\Z');
         $current_row = 0;
         $query_size = 0;
         if (($GLOBALS['sql_insert_syntax'] == 'extended' || $GLOBALS['sql_insert_syntax'] == 'both') && (!isset($GLOBALS['sql_type']) || $GLOBALS['sql_type'] != 'UPDATE')) {
             $separator = ',';
             $schema_insert .= $crlf;
         } else {
             $separator = ';';
         }
         while ($row = PMA_DBI_fetch_row($result)) {
             if ($current_row == 0) {
                 $head = $this->_possibleCRLF() . $this->_exportComment() . $this->_exportComment(__('Dumping data for table') . ' ' . $formatted_table_name) . $this->_exportComment() . $crlf;
                 if (!PMA_exportOutputHandler($head)) {
                     return false;
                 }
             }
             // We need to SET IDENTITY_INSERT ON for MSSQL
             if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] == 'MSSQL' && $current_row == 0) {
                 if (!PMA_exportOutputHandler('SET IDENTITY_INSERT ' . PMA_Util::backquoteCompat($table, $compat) . ' ON ;' . $crlf)) {
                     return false;
                 }
             }
             $current_row++;
             for ($j = 0; $j < $fields_cnt; $j++) {
                 // NULL
                 if (!isset($row[$j]) || is_null($row[$j])) {
                     $values[] = 'NULL';
                 } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp' && !$fields_meta[$j]->blob) {
                     // a number
                     // timestamp is numeric on some MySQL 4.1, BLOBs are
                     // sometimes numeric
                     $values[] = $row[$j];
                 } elseif (stristr($field_flags[$j], 'BINARY') && $fields_meta[$j]->blob && isset($GLOBALS['sql_hex_for_blob'])) {
                     // a true BLOB
                     // - mysqldump only generates hex data when the --hex-blob
                     //   option is used, for fields having the binary attribute
                     //   no hex is generated
                     // - a TEXT field returns type blob but a real blob
                     //   returns also the 'binary' flag
                     // empty blobs need to be different, but '0' is also empty
                     // :-(
                     if (empty($row[$j]) && $row[$j] != '0') {
                         $values[] = '\'\'';
                     } else {
                         $values[] = '0x' . bin2hex($row[$j]);
                     }
                 } elseif ($fields_meta[$j]->type == 'bit') {
                     // detection of 'bit' works only on mysqli extension
                     $values[] = "b'" . PMA_Util::sqlAddSlashes(PMA_Util::printableBitValue($row[$j], $fields_meta[$j]->length)) . "'";
                 } else {
                     // something else -> treat as a string
                     $values[] = '\'' . str_replace($search, $replace, PMA_Util::sqlAddSlashes($row[$j])) . '\'';
                 }
                 // end if
             }
             // end for
             // should we make update?
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
                 $insert_line = $schema_insert;
                 for ($i = 0; $i < $fields_cnt; $i++) {
                     if (0 == $i) {
                         $insert_line .= ' ';
                     }
                     if ($i > 0) {
                         // avoid EOL blank
                         $insert_line .= ',';
                     }
                     $insert_line .= $field_set[$i] . ' = ' . $values[$i];
                 }
                 list($tmp_unique_condition, $tmp_clause_is_unique) = PMA_Util::getUniqueCondition($result, $fields_cnt, $fields_meta, $row);
                 $insert_line .= ' WHERE ' . $tmp_unique_condition;
                 unset($tmp_unique_condition, $tmp_clause_is_unique);
             } else {
                 // Extended inserts case
                 if ($GLOBALS['sql_insert_syntax'] == 'extended' || $GLOBALS['sql_insert_syntax'] == 'both') {
                     if ($current_row == 1) {
                         $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
                     } else {
                         $insert_line = '(' . implode(', ', $values) . ')';
                         $sql_max_size = $GLOBALS['sql_max_query_size'];
                         if (isset($sql_max_size) && $sql_max_size > 0 && $query_size + strlen($insert_line) > $sql_max_size) {
                             if (!PMA_exportOutputHandler(';' . $crlf)) {
                                 return false;
                             }
                             $query_size = 0;
                             $current_row = 1;
                             $insert_line = $schema_insert . $insert_line;
                         }
                     }
                     $query_size += strlen($insert_line);
                     // Other inserts case
                 } else {
                     $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
                 }
             }
             unset($values);
             if (!PMA_exportOutputHandler(($current_row == 1 ? '' : $separator . $crlf) . $insert_line)) {
                 return false;
             }
         }
         // end while
         if ($current_row > 0) {
             if (!PMA_exportOutputHandler(';' . $crlf)) {
                 return false;
             }
         }
         // We need to SET IDENTITY_INSERT OFF for MSSQL
         if (isset($GLOBALS['sql_compatibility']) && $GLOBALS['sql_compatibility'] == 'MSSQL' && $current_row > 0) {
             $outputSucceeded = PMA_exportOutputHandler($crlf . 'SET IDENTITY_INSERT ' . PMA_Util::backquoteCompat($table, $compat) . ' OFF;' . $crlf);
             if (!$outputSucceeded) {
                 return false;
             }
         }
     }
     // end if ($result != false)
     PMA_DBI_free_result($result);
     return true;
 }
Пример #21
0
 /**
  * Outputs the content of a table in JSON format
  *
  * @param string $db        database name
  * @param string $table     table name
  * @param string $crlf      the end of line sequence
  * @param string $error_url the url to go back in case of error
  * @param string $sql_query SQL query for obtaining data
  *
  * @return bool Whether it succeeded
  */
 public function exportData($db, $table, $crlf, $error_url, $sql_query)
 {
     $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
     $columns_cnt = PMA_DBI_num_fields($result);
     // Get field information
     $fields_meta = PMA_DBI_get_fields_meta($result);
     for ($i = 0; $i < $columns_cnt; $i++) {
         $columns[$i] = stripslashes(PMA_DBI_field_name($result, $i));
     }
     unset($i);
     $buffer = '';
     $record_cnt = 0;
     while ($record = PMA_DBI_fetch_row($result)) {
         $record_cnt++;
         // Output table name as comment if this is the first record of the table
         if ($record_cnt == 1) {
             $buffer .= '// ' . $db . '.' . $table . $crlf . $crlf;
             $buffer .= '[{';
         } else {
             $buffer .= ', {';
         }
         for ($i = 0; $i < $columns_cnt; $i++) {
             $isLastLine = $i + 1 >= $columns_cnt;
             $column = $columns[$i];
             if (is_null($record[$i])) {
                 $buffer .= '"' . addslashes($column) . '": null' . (!$isLastLine ? ',' : '');
             } elseif ($fields_meta[$i]->numeric) {
                 $buffer .= '"' . addslashes($column) . '": ' . $record[$i] . (!$isLastLine ? ',' : '');
             } else {
                 $buffer .= '"' . addslashes($column) . '": "' . addslashes($record[$i]) . '"' . (!$isLastLine ? ',' : '');
             }
         }
         $buffer .= '}';
     }
     if ($record_cnt) {
         $buffer .= ']';
     }
     if (!PMA_exportOutputHandler($buffer)) {
         return false;
     }
     PMA_DBI_free_result($result);
     return true;
 }
Пример #22
0
    $found_unique_key = false;
    $where_clauses = array();
    foreach ($where_clause_array as $key_id => $where_clause) {
        $local_query = 'SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . ' WHERE ' . $where_clause . ';';
        $result[$key_id] = PMA_DBI_query($local_query, null, PMA_DBI_QUERY_STORE);
        $rows[$key_id] = PMA_DBI_fetch_assoc($result[$key_id]);
        $where_clauses[$key_id] = str_replace('\\', '\\\\', $where_clause);
        // No row returned
        if (!$rows[$key_id]) {
            unset($rows[$key_id], $where_clause_array[$key_id]);
            PMA_showMessage($strEmptyResultSet, $local_query);
            echo "\n";
            require_once './libraries/footer.inc.php';
        } else {
            // end if (no row returned)
            $meta = PMA_DBI_get_fields_meta($result[$key_id]);
            list($unique_condition, $tmp_clause_is_unique) = PMA_getUniqueCondition($result[$key_id], count($meta), $meta, $rows[$key_id], true);
            if (!empty($unique_condition)) {
                $found_unique_key = true;
            }
            unset($unique_condition, $tmp_clause_is_unique);
        }
    }
} else {
    // no primary key given, just load first row - but what happens if table is empty?
    $insert_mode = true;
    $result = PMA_DBI_query('SELECT * FROM ' . PMA_backquote($db) . '.' . PMA_backquote($table) . ' LIMIT 1;', null, PMA_DBI_QUERY_STORE);
    $rows = array_fill(0, $cfg['InsertRows'], false);
}
// <*****@*****.**>
// retrieve keys into foreign fields, if any
Пример #23
0
 /**
  * Dispatches between the versions of 'getTableContent' to use depending
  * on the php version
  *
  * @param   string      the database name
  * @param   string      the table name
  * @param   string      the end of line sequence
  * @param   string      the url to go back in case of error
  * @param   string      SQL query for obtaining data
  *
  * @return  bool        Whether it suceeded
  *
  * @global  boolean  whether to use backquotes to allow the use of special
  *                   characters in database, table and fields names or not
  * @global  integer  the number of records
  * @global  integer  the current record position
  *
  * @access  public
  *
  * @see     PMA_getTableContentFast(), PMA_getTableContentOld()
  *
  * @author  staybyte
  */
 function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
 {
     global $sql_backquotes;
     global $rows_cnt;
     global $current_row;
     $formatted_table_name = isset($GLOBALS['sql_backquotes']) ? PMA_backquote($table) : '\'' . $table . '\'';
     $head = $crlf . $GLOBALS['comment_marker'] . $crlf . $GLOBALS['comment_marker'] . $GLOBALS['strDumpingData'] . ' ' . $formatted_table_name . $crlf . $GLOBALS['comment_marker'] . $crlf . $crlf;
     if (!PMA_exportOutputHandler($head)) {
         return FALSE;
     }
     $buffer = '';
     // analyze the query to get the true column names, not the aliases
     // (this fixes an undefined index, also if Complete inserts
     //  are used, we did not get the true column name in case of aliases)
     $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($sql_query));
     $result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
     if ($result != FALSE) {
         $fields_cnt = PMA_DBI_num_fields($result);
         // Get field information
         $fields_meta = PMA_DBI_get_fields_meta($result);
         $field_flags = array();
         for ($j = 0; $j < $fields_cnt; $j++) {
             $field_flags[$j] = PMA_DBI_field_flags($result, $j);
         }
         for ($j = 0; $j < $fields_cnt; $j++) {
             if (isset($analyzed_sql[0]['select_expr'][$j]['column'])) {
                 $field_set[$j] = PMA_backquote($analyzed_sql[0]['select_expr'][$j]['column'], $sql_backquotes);
             } else {
                 $field_set[$j] = PMA_backquote($fields_meta[$j]->name, $sql_backquotes);
             }
         }
         if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
             // update
             $schema_insert = 'UPDATE ';
             if (isset($GLOBALS['sql_ignore'])) {
                 $schema_insert .= 'IGNORE ';
             }
             $schema_insert .= PMA_backquote($table, $sql_backquotes) . ' SET ';
         } else {
             // insert or replace
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'REPLACE') {
                 $sql_command = 'REPLACE';
             } else {
                 $sql_command = 'INSERT';
             }
             // delayed inserts?
             if (isset($GLOBALS['sql_delayed'])) {
                 $insert_delayed = ' DELAYED';
             } else {
                 $insert_delayed = '';
             }
             // insert ignore?
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'INSERT' && isset($GLOBALS['sql_ignore'])) {
                 $insert_delayed .= ' IGNORE';
             }
             // scheme for inserting fields
             if (isset($GLOBALS['sql_columns'])) {
                 $fields = implode(', ', $field_set);
                 $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_backquote($table, $sql_backquotes) . ' (' . $fields . ') VALUES ';
             } else {
                 $schema_insert = $sql_command . $insert_delayed . ' INTO ' . PMA_backquote($table, $sql_backquotes) . ' VALUES ';
             }
         }
         $search = array("", "\n", "\r", "");
         //\x08\\x09, not required
         $replace = array('\\0', '\\n', '\\r', '\\Z');
         $current_row = 0;
         $query_size = 0;
         if (isset($GLOBALS['sql_extended']) && (!isset($GLOBALS['sql_type']) || $GLOBALS['sql_type'] != 'UPDATE')) {
             $separator = ',';
             $schema_insert .= $crlf;
         } else {
             $separator = ';';
         }
         while ($row = PMA_DBI_fetch_row($result)) {
             $current_row++;
             for ($j = 0; $j < $fields_cnt; $j++) {
                 // NULL
                 if (!isset($row[$j]) || is_null($row[$j])) {
                     $values[] = 'NULL';
                     // a number
                     // timestamp is numeric on some MySQL 4.1, BLOBs are sometimes numeric
                 } elseif ($fields_meta[$j]->numeric && $fields_meta[$j]->type != 'timestamp' && !$fields_meta[$j]->blob) {
                     $values[] = $row[$j];
                     // a binary field
                     // Note: with mysqli, under MySQL 4.1.3, we get the flag
                     // "binary" for those field types (I don't know why)
                 } elseif (stristr($field_flags[$j], 'BINARY') && isset($GLOBALS['sql_hex_for_binary']) && $fields_meta[$j]->type != 'datetime' && $fields_meta[$j]->type != 'date' && $fields_meta[$j]->type != 'time' && $fields_meta[$j]->type != 'timestamp') {
                     // empty blobs need to be different, but '0' is also empty :-(
                     if (empty($row[$j]) && $row[$j] != '0') {
                         $values[] = '\'\'';
                     } else {
                         $values[] = '0x' . bin2hex($row[$j]);
                     }
                     // something else -> treat as a string
                 } else {
                     $values[] = '\'' . str_replace($search, $replace, PMA_sqlAddslashes($row[$j])) . '\'';
                 }
                 // end if
             }
             // end for
             // should we make update?
             if (isset($GLOBALS['sql_type']) && $GLOBALS['sql_type'] == 'UPDATE') {
                 $insert_line = $schema_insert;
                 for ($i = 0; $i < $fields_cnt; $i++) {
                     if ($i > 0) {
                         $insert_line .= ', ';
                     }
                     $insert_line .= $field_set[$i] . ' = ' . $values[$i];
                 }
                 $insert_line .= ' WHERE ' . PMA_getUniqueCondition($result, $fields_cnt, $fields_meta, $row);
             } else {
                 // Extended inserts case
                 if (isset($GLOBALS['sql_extended'])) {
                     if ($current_row == 1) {
                         $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
                     } else {
                         $insert_line = '(' . implode(', ', $values) . ')';
                         if (isset($GLOBALS['sql_max_query_size']) && $GLOBALS['sql_max_query_size'] > 0 && $query_size + strlen($insert_line) > $GLOBALS['sql_max_query_size']) {
                             if (!PMA_exportOutputHandler(';' . $crlf)) {
                                 return FALSE;
                             }
                             $query_size = 0;
                             $current_row = 1;
                             $insert_line = $schema_insert . $insert_line;
                         }
                     }
                     $query_size += strlen($insert_line);
                 } else {
                     $insert_line = $schema_insert . '(' . implode(', ', $values) . ')';
                 }
             }
             unset($values);
             if (!PMA_exportOutputHandler(($current_row == 1 ? '' : $separator . $crlf) . $insert_line)) {
                 return FALSE;
             }
         }
         // end while
         if ($current_row > 0) {
             if (!PMA_exportOutputHandler(';' . $crlf)) {
                 return FALSE;
             }
         }
     }
     // end if ($result != FALSE)
     PMA_DBI_free_result($result);
     return TRUE;
 }
Пример #24
0
if (!isset($_POST['zoom_submit']) || $_POST['dataLabel'] == '') {
    $dataLabel = PMA_getDisplayField($db, $table);
}
// Displays the zoom search form
$response->addHTML($table_search->getSelectionForm($goto, $dataLabel));
/*
 * Handle the input criteria and generate the query result
 * Form for displaying query results
 */
if (isset($zoom_submit) && $_POST['criteriaColumnNames'][0] != 'pma_null' && $_POST['criteriaColumnNames'][1] != 'pma_null' && $_POST['criteriaColumnNames'][0] != $_POST['criteriaColumnNames'][1]) {
    //Query generation part
    $sql_query = $table_search->buildSqlQuery();
    $sql_query .= ' LIMIT ' . $maxPlotLimit;
    //Query execution part
    $result = PMA_DBI_query($sql_query . ";", null, PMA_DBI_QUERY_STORE);
    $fields_meta = PMA_DBI_get_fields_meta($result);
    while ($row = PMA_DBI_fetch_assoc($result)) {
        //Need a row with indexes as 0,1,2 for the getUniqueCondition
        // hence using a temporary array
        $tmpRow = array();
        foreach ($row as $val) {
            $tmpRow[] = $val;
        }
        //Get unique conditon on each row (will be needed for row update)
        $uniqueCondition = PMA_Util::getUniqueCondition($result, count($table_search->getColumnNames()), $fields_meta, $tmpRow, true);
        //Append it to row array as where_clause
        $row['where_clause'] = $uniqueCondition[0];
        $tmpData = array($_POST['criteriaColumnNames'][0] => $row[$_POST['criteriaColumnNames'][0]], $_POST['criteriaColumnNames'][1] => $row[$_POST['criteriaColumnNames'][1]], 'where_clause' => $uniqueCondition[0]);
        $tmpData[$dataLabel] = $dataLabel ? $row[$dataLabel] : '';
        $data[] = $tmpData;
    }
Пример #25
0
function PMA_getTableContentFast($db, $table, $add_query = "", $handler, $exptype)
{
    global $current_row, $rows_cnt, $crlf;
    // Поулучаем число записей, т.к mysql_num_rows не поддреживается с unbuffed_query
    $query = "SELECT COUNT(*) FROM " . PMA_backquote($db) . "." . PMA_backquote($table) . $add_query;
    $r = mysql_unbuffered_query($query);
    $rows_cnt = mysql_fetch_row($r);
    $rows_cnt = $rows_cnt[0];
    mysql_free_result($r);
    $local_query = "SELECT * FROM " . PMA_backquote($db) . "." . PMA_backquote($table) . $add_query;
    $result = mysql_unbuffered_query($local_query) or die($local_query);
    if ($result != FALSE) {
        $fields_cnt = mysql_num_fields($result);
        //$rows_cnt   = mysql_num_rows($result);
        // Get field information
        $fields_meta = PMA_DBI_get_fields_meta($result);
        $field_flags = array();
        for ($j = 0; $j < $fields_cnt; $j++) {
            $field_flags[$j] = PMA_DBI_field_flags($result, $j);
        }
        // Checks whether the field is an integer or not
        for ($j = 0; $j < $fields_cnt; $j++) {
            $field_set[$j] = PMA_backquote(mysql_field_name($result, $j), $GLOBALS["_POST"]["use_backquotes"]);
            $type = mysql_field_type($result, $j);
            if (strpos($type, "int") !== false) {
                $field_num[$j] = TRUE;
            } else {
                $field_num[$j] = FALSE;
            }
        }
        // end for
        switch ($exptype) {
            case "einsert":
                if (isset($GLOBALS["_POST"]["showcolumns"])) {
                    $fields = implode(", ", $field_set);
                    $schema_insert = "INSERT INTO " . PMA_backquote($table, $GLOBALS["_POST"]["use_backquotes"]) . " (" . $fields . ") VALUES (";
                } else {
                    $schema_insert = "INSERT INTO " . PMA_backquote($table, $GLOBALS["_POST"]["use_backquotes"]) . " VALUES (";
                }
                $mode = 'ins';
                break;
            case "ereplace":
                if (isset($GLOBALS["_POST"]["showcolumns"])) {
                    $fields = implode(", ", $field_set);
                    $schema_insert = "REPLACE INTO " . PMA_backquote($table, $GLOBALS["_POST"]["use_backquotes"]) . " (" . $fields . ") VALUES (";
                } else {
                    $schema_insert = "REPLACE INTO " . PMA_backquote($table, $GLOBALS["_POST"]["use_backquotes"]) . " VALUES (";
                }
                $mode = 'ins';
                break;
            case "eupdate":
                $schema_insert = "UPDATE " . PMA_backquote($table, $GLOBALS["_POST"]["use_backquotes"]) . " SET ";
                $mode = 'upd';
                $pkeys = array();
                $npkeys = array();
                for ($j = 0; $j < $fields_cnt; $j++) {
                    if (strpos($field_flags[$j], 'primary_key') !== false) {
                        $pkeys[$j] = $field_set[$j];
                    } else {
                        $npkeys[$j] = $field_set[$j];
                    }
                }
                /*///////////////////////////////////////////////////////////////////////////
                		if (count($pkeys)<1)
                		{
                    		pr($pkeys);
                    		pr($npkeys);
                    		pr($field_flags);
                    		die();
                		}
                        */
                break;
        }
        // Sets the scheme
        $search = array("", "\n", "\r", "");
        //\x08\\x09, not required
        $replace = array("\\0", "\\n", "\\r", "\\Z");
        $current_row = 0;
        // loic1: send a fake header to bypass browser timeout if data
        //		are bufferized - part 1
        if (!empty($GLOBALS["ob_mode"]) || (isset($GLOBALS["_POST"]["zip"]) || isset($GLOBALS["_POST"]["bzip"]) || isset($GLOBALS["_POST"]["gzip"]))) {
            $time0 = time();
        }
        while ($row = mysql_fetch_row($result)) {
            $current_row++;
            for ($j = 0; $j < $fields_cnt; $j++) {
                if (!isset($row[$j])) {
                    $values[] = "NULL";
                } else {
                    if ($row[$j] == "0" || $row[$j] != "") {
                        // a number
                        if ($field_num[$j]) {
                            $values[] = $row[$j];
                        } else {
                            $values[] = "'" . str_replace($search, $replace, PMA_sqlAddslashes($row[$j])) . "'";
                        }
                    } else {
                        $values[] = "''";
                    }
                }
                // end if
            }
            // end for
            if ($exptype != 'eupdate') {
                // Extended inserts case
                if (isset($GLOBALS["_POST"]["extended_ins"])) {
                    if ($current_row == 1 || !($current_row % EXT_INC_COL)) {
                        $insert_line = $schema_insert . implode(", ", $values) . ")";
                    } else {
                        $insert_line = "(" . implode(", ", $values) . ")";
                    }
                } else {
                    $insert_line = $schema_insert . implode(", ", $values) . ")";
                }
            } else {
                $tmpnp = array();
                $tmpp = array();
                foreach ($npkeys as $k => $np) {
                    $tmpnp[] = $np . ' = ' . $values[$k];
                }
                foreach ($pkeys as $k => $pp) {
                    $tmpp[] = $pp . ' = ' . $values[$k];
                }
                $insert_line = $schema_insert . implode(', ', $tmpnp) . ' WHERE ' . implode(' AND ', $tmpp);
                unset($tmpnp);
                unset($tmpp);
            }
            unset($values);
            // Call the handler
            $handler($insert_line);
            // loic1: send a fake header to bypass browser timeout if data
            // are bufferized - part 2
            if (isset($time0)) {
                $time1 = time();
                if ($time1 >= $time0 + 1) {
                    $time0 = $time1;
                    echo ".\n\r";
                    flush();
                    ob_flush();
                }
            }
            // end if
        }
        // end while
    }
    // end if ($result != FALSE)
    mysql_free_result($result);
    return TRUE;
}