$val = "''";
}
if (isset($out[$key])) {
- $connection->query("SET @" . idf_escape($field["field"]) . " = $val");
+ connection()->query("SET @" . idf_escape($field["field"]) . " = $val");
}
}
$call[] = (isset($out[$key]) ? "@" . idf_escape($field["field"]) : $val);
$query = (isset($_GET["callf"]) ? "SELECT" : "CALL") . " " . table($PROCEDURE) . "(" . implode(", ", $call) . ")";
$start = microtime(true);
- $result = $connection->multi_query($query);
- $affected = $connection->affected_rows; // getting warnings overwrites this
+ $result = connection()->multi_query($query);
+ $affected = connection()->affected_rows; // getting warnings overwrites this
echo adminer()->selectQuery($query, $start, !$result);
if (!$result) {
}
do {
- $result = $connection->store_result();
+ $result = connection()->store_result();
if (is_object($result)) {
print_select_result($result, $connection2);
} else {
. " <span class='time'>" . @date("H:i:s") . "</span>\n" // @ - time zone may be not set
;
}
- } while ($connection->next_result());
+ } while (connection()->next_result());
if ($out) {
- print_select_result($connection->query("SELECT " . implode(", ", $out)));
+ print_select_result(connection()->query("SELECT " . implode(", ", $out)));
}
}
}
}
function last_id($result) {
- global $connection;
- return $connection->lastInsertId();
+ return connection()->lastInsertId();
}
function explain($connection, $query) {
}
function count_tables($databases) {
- global $connection;
$return = array();
foreach ($databases as $db) {
- $connection->select_db($db);
+ connection()->select_db($db);
$return[$db] = get_val("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES");
}
return $return;
}
function error() {
- global $connection;
- return nl_br(h(preg_replace('~^(\[[^]]*])+~m', '', $connection->error)));
+ return nl_br(h(preg_replace('~^(\[[^]]*])+~m', '', connection()->error)));
}
function create_database($db, $collation) {
// MySQLi supports everything, MySQL doesn't support multiple result sets, PDO_MySQL doesn't support orgtable
if (extension_loaded("mysqli") && $_GET["ext"] != "pdo") {
class Db extends \MySQLi {
+ /** @var Db|string */ static $instance = '';
public string $extension = "MySQLi", $flavor = '';
function __construct() {
* @return Field[]
*/
function fields(string $table): array {
- global $connection;
- $maria = ($connection->flavor == 'maria');
+ $maria = (connection()->flavor == 'maria');
$return = array();
foreach (get_rows("SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = " . q($table) . " ORDER BY ORDINAL_POSITION") as $row) {
$field = $row["COLUMN_NAME"];
/** Get escaped error message */
function error(): string {
- global $connection;
- return h(preg_replace('~^You have an error.*syntax to use~U', "Syntax error", $connection->error));
+ return h(preg_replace('~^You have an error.*syntax to use~U', "Syntax error", connection()->error));
}
/** Create database
* @return Result|bool
*/
function alter_table(string $table, string $name, array $fields, array $foreign, ?string $comment, string $engine, string $collation, string $auto_increment, string $partitioning) {
- global $connection;
$alter = array();
foreach ($fields as $field) {
if ($field[1]) {
$default = $field[1][3];
if (preg_match('~ GENERATED~', $default)) {
// swap default and null
- $field[1][3] = ($connection->flavor == 'maria' ? "" : $field[1][2]); // MariaDB doesn't support NULL on virtual columns
+ $field[1][3] = (connection()->flavor == 'maria' ? "" : $field[1][2]); // MariaDB doesn't support NULL on virtual columns
$field[1][2] = $default;
}
$alter[] = ($table != "" ? ($field[0] != "" ? "CHANGE " . idf_escape($field[0]) : "ADD") : " ") . " " . implode($field[1]) . ($table != "" ? $field[2] : "");
* @param list<string> $views
*/
function move_tables(array $tables, array $views, string $target): bool {
- global $connection;
$rename = array();
foreach ($tables as $table) {
$rename[] = table($table) . " TO " . idf_escape($target) . "." . table($table);
foreach ($views as $table) {
$definitions[table($table)] = view($table);
}
- $connection->select_db($target);
+ connection()->select_db($target);
$db = idf_escape(DB);
foreach ($definitions as $name => $view) {
if (!queries("CREATE VIEW $name AS " . str_replace(" $db.", " ", $view["select"])) || !queries("DROP VIEW $db.$name")) {
}
function insertUpdate(string $table, array $rows, array $primary) {
- global $connection;
foreach ($rows as $set) {
$update = array();
$where = array();
}
}
if (
- !(($where && queries("UPDATE " . table($table) . " SET " . implode(", ", $update) . " WHERE " . implode(" AND ", $where)) && $connection->affected_rows)
+ !(($where && queries("UPDATE " . table($table) . " SET " . implode(", ", $update) . " WHERE " . implode(" AND ", $where)) && connection()->affected_rows)
|| queries("INSERT INTO " . table($table) . " (" . implode(", ", array_keys($set)) . ") VALUES (" . implode(", ", $set) . ")"))
) {
return false;
}
function get_current_db() {
- global $connection;
- $db = $connection->_current_db ?: DB;
- unset($connection->_current_db);
+ $db = connection()->_current_db ?: DB;
+ unset(connection()->_current_db);
return $db;
}
}
function error() {
- global $connection;
- return h($connection->error); //! highlight sqltext from offset
+ return h(connection()->error); //! highlight sqltext from offset
}
function explain($connection, $query) {
}
function set_schema($scheme, $connection2 = null) {
- global $connection;
if (!$connection2) {
- $connection2 = $connection;
+ $connection2 = connection();
}
return $connection2->query("ALTER SESSION SET CURRENT_SCHEMA = " . idf_escape($scheme));
}
}
function insertUpdate(string $table, array $rows, array $primary) {
- global $connection;
foreach ($rows as $set) {
$update = array();
$where = array();
}
}
if (
- !(($where && queries("UPDATE " . table($table) . " SET " . implode(", ", $update) . " WHERE " . implode(" AND ", $where)) && $connection->affected_rows)
+ !(($where && queries("UPDATE " . table($table) . " SET " . implode(", ", $update) . " WHERE " . implode(" AND ", $where)) && connection()->affected_rows)
|| queries("INSERT INTO " . table($table) . " (" . implode(", ", array_keys($set)) . ") VALUES (" . implode(", ", $set) . ")"))
) {
return false;
}
function count_tables($databases) {
- global $connection;
$return = array();
foreach ($databases as $db) {
- if ($connection->select_db($db)) {
+ if (connection()->select_db($db)) {
$return[$db] = count(tables_list());
}
}
}
function indexes($table, $connection2 = null) {
- global $connection;
if (!is_object($connection2)) {
- $connection2 = $connection;
+ $connection2 = connection();
}
$return = array();
$table_oid = get_val("SELECT oid FROM pg_class WHERE relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = current_schema()) AND relname = " . q($table), 0, $connection2);
}
function error() {
- global $connection;
- $return = h($connection->error);
+ $return = h(connection()->error);
if (preg_match('~^(.*\n)?([^\n]*)\n( *)\^(\n.*)?$~s', $return, $match)) {
$return = $match[1] . preg_replace('~((?:[^&]|&[^;]*;){' . strlen($match[3]) . '})(.*)~', '\1<b>\2</b>', $match[2]) . $match[4];
}
}
function drop_databases($databases) {
- global $connection;
- $connection->close();
+ connection()->close();
return apply_queries("DROP DATABASE", $databases, 'Adminer\idf_escape');
}
function rename_database($name, $collation) {
- global $connection;
- $connection->close();
+ connection()->close();
return queries("ALTER DATABASE " . idf_escape(DB) . " RENAME TO " . idf_escape($name));
}
}
function set_schema($schema, $connection2 = null) {
- global $connection;
if (!$connection2) {
- $connection2 = $connection;
+ $connection2 = connection();
}
$return = $connection2->query("SET search_path TO " . idf_escape($schema));
driver()->setUserTypes(types()); //! get types from current_schemas('t')
}
function support($feature) {
- global $connection;
return preg_match('~^(check|database|table|columns|sql|indexes|descidx|comment|view|' . (min_version(9.3) ? 'materializedview|' : '') . 'scheme|' . (min_version(11) ? 'procedure|' : '') . 'routine|sequence|trigger|type|variables|drop_col'
- . ($connection->flavor == 'cockroach' ? '' : '|processlist') // https://github.com/cockroachdb/cockroach/issues/24745
+ . (connection()->flavor == 'cockroach' ? '' : '|processlist') // https://github.com/cockroachdb/cockroach/issues/24745
. '|kill|dump)$~', $feature)
;
}
}
function indexes($table, $connection2 = null) {
- global $connection;
if (!is_object($connection2)) {
- $connection2 = $connection;
+ $connection2 = connection();
}
$return = array();
$sql = get_val("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = " . q($table), 0, $connection2);
}
function error() {
- global $connection;
- return h($connection->error);
+ return h(connection()->error);
}
function check_sqlite_name($name) {
// avoid creating PHP files on unsecured servers
- global $connection;
$extensions = "db|sdb|sqlite";
if (!preg_match("~^[^\\0]*\\.($extensions)\$~", $name)) {
- $connection->error = lang('Please use one of the extensions %s.', str_replace("|", ", ", $extensions));
+ connection()->error = lang('Please use one of the extensions %s.', str_replace("|", ", ", $extensions));
return false;
}
return true;
}
function create_database($db, $collation) {
- global $connection;
if (file_exists($db)) {
- $connection->error = lang('File exists.');
+ connection()->error = lang('File exists.');
return false;
}
if (!check_sqlite_name($db)) {
$link = new Db();
$link->attach($db, '', '');
} catch (\Exception $ex) {
- $connection->error = $ex->getMessage();
+ connection()->error = $ex->getMessage();
return false;
}
$link->query('PRAGMA encoding = "UTF-8"');
}
function drop_databases($databases) {
- global $connection;
- $connection->attach(":memory:", '', ''); // to unlock file, doesn't work in PDO on Windows
+ connection()->attach(":memory:", '', ''); // to unlock file, doesn't work in PDO on Windows
foreach ($databases as $db) {
if (!@unlink($db)) {
- $connection->error = lang('File exists.');
+ connection()->error = lang('File exists.');
return false;
}
}
}
function rename_database($name, $collation) {
- global $connection;
if (!check_sqlite_name($name)) {
return false;
}
- $connection->attach(":memory:", '', '');
- $connection->error = lang('File exists.');
+ connection()->attach(":memory:", '', '');
+ connection()->error = lang('File exists.');
return @rename(DB, $name);
}
}
function alter_table($table, $name, $fields, $foreign, $comment, $engine, $collation, $auto_increment, $partitioning) {
- global $connection;
$use_all_fields = ($table == "" || $foreign);
foreach ($fields as $field) {
if ($field[0] != "" || !$field[1] || $field[2]) {
if ($auto_increment) {
queries("BEGIN");
queries("UPDATE sqlite_sequence SET seq = $auto_increment WHERE name = " . q($name)); // ignores error
- if (!$connection->affected_rows) {
+ if (!connection()->affected_rows) {
queries("INSERT INTO sqlite_sequence (name, seq) VALUES (" . q($name) . ", $auto_increment)");
}
queries("COMMIT");
}
$temp_name = ($table == $name ? "adminer_$name" : $name);
if (!queries("CREATE TABLE " . table($temp_name) . " (\n" . implode(",\n", $changes) . "\n)")) {
- // implicit ROLLBACK to not overwrite $connection->error
+ // implicit ROLLBACK to not overwrite connection()->error
return false;
}
if ($table != "") {
$is_sql = preg_match('~sql~', $_POST["format"]);
if ($is_sql) {
- echo "-- Adminer " . VERSION . " " . get_driver(DRIVER) . " " . str_replace("\n", " ", $connection->server_info) . " dump\n\n";
+ echo "-- Adminer " . VERSION . " " . get_driver(DRIVER) . " " . str_replace("\n", " ", connection()->server_info) . " dump\n\n";
if (JUSH == "sql") {
echo "SET NAMES utf8;
SET time_zone = '+00:00';
" . ($_POST["data_style"] ? "SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
" : "") . "
";
- $connection->query("SET time_zone = '+00:00'");
- $connection->query("SET sql_mode = ''");
+ connection()->query("SET time_zone = '+00:00'");
+ connection()->query("SET sql_mode = ''");
}
}
foreach ((array) $databases as $db) {
adminer()->dumpDatabase($db);
- if ($connection->select_db($db)) {
+ if (connection()->select_db($db)) {
if ($is_sql && preg_match('~CREATE~', $style) && ($create = get_val("SHOW CREATE DATABASE " . idf_escape($db), 1))) {
set_utf8mb4($create);
if ($style == "DROP+CREATE") {
<?php
$source = array_keys(fields($TABLE)); //! no text and blob
if ($row["db"] != "") {
- $connection->select_db($row["db"]);
+ connection()->select_db($row["db"]);
}
if ($row["ns"] != "") {
$orig_schema = get_schema();
* @return list<string> expressions to join by AND
*/
function selectSearchProcess(array $fields, array $indexes): array {
- global $connection;
$return = array();
foreach ($indexes as $i => $index) {
if ($index["type"] == "FULLTEXT" && $_GET["fulltext"][$i] != "") {
* @return void prints data
*/
function dumpData(string $table, string $style, string $query): void {
- global $connection;
if ($style) {
$max_packet = (JUSH == "sqlite" ? 0 : 1048576); // default, minimum is 1024
$fields = array();
}
}
}
- $result = $connection->query($query, 1); // 1 - MYSQLI_USE_RESULT //! enum and set as numbers
+ $result = connection()->query($query, 1); // 1 - MYSQLI_USE_RESULT //! enum and set as numbers
if ($result) {
$insert = "";
$buffer = "";
echo $buffer . $suffix;
}
} elseif ($_POST["format"] == "sql") {
- echo "-- " . str_replace("\n", " ", $connection->error) . "\n";
+ echo "-- " . str_replace("\n", " ", connection()->error) . "\n";
}
if ($identity_insert) {
echo "SET IDENTITY_INSERT " . table($table) . " OFF;\n";
* @param string $missing can be "auth" if there is no database connection, "db" if there is no database selected, "ns" with invalid schema
*/
function navigation(string $missing): void {
- global $connection;
echo "<h1>" . adminer()->name() . " <span class='version'>" . VERSION;
$new_version = $_COOKIE["adminer_version"];
echo " <a href='https://www.adminer.org/#download'" . target_blank() . " id='version'>" . (version_compare(VERSION, $new_version) < 0 ? h($new_version) : "") . "</a>";
} else {
$tables = array();
if ($_GET["ns"] !== "" && !$missing && DB != "") {
- $connection->select_db(DB);
+ connection()->select_db(DB);
$tables = table_status('', true);
}
adminer()->syntaxHighlighting($tables);
* @param TableStatus[] $tables
*/
function syntaxHighlighting(array $tables): void {
- global $connection;
// this is matched by compile.php
echo script_src("../externals/jush/modules/jush.js");
echo script_src("../externals/jush/modules/jush-textarea.js");
}
echo "</script>\n";
}
- echo script("syntaxHighlighting('" . (is_object($connection) ? preg_replace('~^(\d\.?\d).*~s', '\1', $connection->server_info) : "") . "'"
- . ($connection->flavor == 'maria' ? ", 'maria'" : ($connection->flavor == 'cockroach' ? ", 'cockroach'" : "")) . ");"
+ echo script("syntaxHighlighting('" . (is_object(connection()) ? preg_replace('~^(\d\.?\d).*~s', '\1', connection()->server_info) : "") . "'"
+ . (connection()->flavor == 'maria' ? ", 'maria'" : (connection()->flavor == 'cockroach' ? ", 'cockroach'" : "")) . ");"
);
}
/** Print databases list in menu */
function databasesPrint(string $missing): void {
- global $connection;
$databases = adminer()->databases();
if (DB && $databases && !in_array(DB, $databases)) {
array_unshift($databases, DB);
);
echo "<input type='submit' value='" . lang('Use') . "'" . ($databases ? " class='hidden'" : "") . ">\n";
if (support("scheme")) {
- if ($missing != "db" && DB != "" && $connection->select_db(DB)) {
+ if ($missing != "db" && DB != "" && connection()->select_db(DB)) {
echo "<br><span>" . lang('Schema') . ":</span> " . html_select("ns", array("" => "") + adminer()->schemas(), $_GET["ns"]) . $db_events;
if ($_GET["ns"] != "") {
set_schema($_GET["ns"]);
<?php
namespace Adminer;
-$connection = '';
-
$permanent = array();
if ($_COOKIE["adminer_permanent"]) {
foreach (explode(" ", $_COOKIE["adminer_permanent"]) as $val) {
auth_error(lang('Connecting to privileged ports is not allowed.'), $permanent);
}
check_invalid_login($permanent);
- $connection = connect(adminer()->credentials());
- if (is_object($connection)) {
- Driver::$instance = new Driver($connection);
- if ($connection->flavor) {
+ Db::$instance = connect(adminer()->credentials());
+ if (is_object(Db::$instance)) {
+ Driver::$instance = new Driver(Db::$instance);
+ if (Db::$instance->flavor) {
save_settings(array("vendor-" . DRIVER . "-" . SERVER => get_driver(DRIVER)));
}
}
}
$login = null;
-if (!is_object($connection) || ($login = adminer()->login($_GET["username"], get_password())) !== true) {
- $error = (is_string($connection) ? nl_br(h($connection)) : (is_string($login) ? $login : lang('Invalid credentials.')));
+if (!is_object(connection()) || ($login = adminer()->login($_GET["username"], get_password())) !== true) {
+ $error = (is_string(connection()) ? nl_br(h(connection())) : (is_string($login) ? $login : lang('Invalid credentials.')));
auth_error(
$error . (preg_match('~^ | $~', get_password()) ? '<br>' . lang('There is a space in the input password which might be the cause.') : ''),
$permanent
exit;
}
-global $connection, $translations; // allows including Adminer inside a function
+global $translations; // allows including Adminer inside a function
if (!$_SERVER["REQUEST_URI"]) { // IIS 5 compatibility
$_SERVER["REQUEST_URI"] = $_SERVER["ORIG_PATH_INFO"];
if (
!(DB != ""
- ? $connection->select_db(DB)
+ ? connection()->select_db(DB)
: isset($_GET["sql"]) || isset($_GET["dump"]) || isset($_GET["database"]) || isset($_GET["processlist"]) || isset($_GET["privileges"]) || isset($_GET["user"]) || isset($_GET["variables"])
|| $_GET["script"] == "connect" || $_GET["script"] == "kill"
)
echo "<a href='" . h(ME) . "$key='>$val</a>\n";
}
}
- echo "<p>" . lang('%s version: %s through PHP extension %s', get_driver(DRIVER), "<b>" . h($connection->server_info) . "</b>", "<b>$connection->extension</b>") . "\n";
+ echo "<p>" . lang('%s version: %s through PHP extension %s', get_driver(DRIVER), "<b>" . h(connection()->server_info) . "</b>", "<b>" . connection()->extension . "</b>") . "\n";
echo "<p>" . lang('Logged as: %s', "<b>" . h(logged_user()) . "</b>") . "\n";
if (isset(adminer()->plugins) && is_array(adminer()->plugins)) {
echo "<p>" . lang('Loaded plugins') . ":\n<ul>\n";
// this could be interface when "Db extends \mysqli" can have compatible type declarations (PHP 7)
// interfaces can include properties only since PHP 8.4
abstract class SqlDb {
+ /** @var Db|string */ static $instance = ''; // string means error
+
public string $extension; // extension name
public string $flavor = ''; // different vendor with the same API, e.g. MariaDB; usually stays empty
public string $server_info; // server version
* @return array{partition_by:string, partition:string, partitions:string, partition_names:list<string>, partition_values:list<string>}
*/
function get_partitions_info(string $table): array {
- global $connection;
$from = "FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = " . q(DB) . " AND TABLE_NAME = " . q($table);
- $result = $connection->query("SELECT PARTITION_METHOD, PARTITION_EXPRESSION, PARTITION_ORDINAL_POSITION $from ORDER BY PARTITION_ORDINAL_POSITION DESC LIMIT 1");
+ $result = connection()->query("SELECT PARTITION_METHOD, PARTITION_EXPRESSION, PARTITION_ORDINAL_POSITION $from ORDER BY PARTITION_ORDINAL_POSITION DESC LIMIT 1");
$return = array();
list($return["partition_by"], $return["partition"], $return["partitions"]) = $result->fetch_row();
$partitions = get_key_vals("SELECT PARTITION_NAME, PARTITION_DESCRIPTION $from AND PARTITION_NAME != '' ORDER BY PARTITION_ORDINAL_POSITION");
* @return string HTML code
*/
function doc_link(array $paths, string $text = "<sup>?</sup>"): string {
- global $connection;
- $server_info = $connection->server_info;
+ $server_info = connection()->server_info;
$version = preg_replace('~^(\d\.?\d).*~s', '\1', $server_info); // two most significant digits
$urls = array(
'sql' => "https://dev.mysql.com/doc/refman/$version/en/",
'sqlite' => "https://www.sqlite.org/",
- 'pgsql' => "https://www.postgresql.org/docs/" . ($connection->flavor == 'cockroach' ? "current" : $version) . "/",
+ 'pgsql' => "https://www.postgresql.org/docs/" . (connection()->flavor == 'cockroach' ? "current" : $version) . "/",
'mssql' => "https://learn.microsoft.com/en-us/sql/",
'oracle' => "https://www.oracle.com/pls/topic/lookup?ctx=db" . preg_replace('~^.* (\d+)\.(\d+)\.\d+\.\d+\.\d+.*~s', '\1\2', $server_info) . "&id=",
);
- if ($connection->flavor == 'maria') {
+ if (connection()->flavor == 'maria') {
$urls['sql'] = "https://mariadb.com/kb/en/";
$paths['sql'] = (isset($paths['mariadb']) ? $paths['mariadb'] : str_replace(".html", "/", $paths['sql']));
}
* @return string formatted
*/
function db_size(string $db): string {
- global $connection;
- if (!$connection->select_db($db)) {
+ if (!connection()->select_db($db)) {
return "?";
}
$return = 0;
/** Print SET NAMES if utf8mb4 might be needed */
function set_utf8mb4(string $create): void {
- global $connection;
static $set = false;
if (!$set && preg_match('~\butf8mb4~i', $create)) { // possible false positive
$set = true;
- echo "SET NAMES " . charset($connection) . ";\n\n";
+ echo "SET NAMES " . charset(connection()) . ";\n\n";
}
}
// This file is used both in Adminer and Adminer Editor.
-/** Get database connection */
-function connection(): Db {
- // can be used in customization, $connection is minified
- global $connection;
- return $connection;
+/** Get database connection
+* @return Db|string string means error
+*/
+function connection() {
+ // can be used in customization, Db::$instance is minified
+ return Db::$instance;
}
/** Get Adminer object
return str_replace($last . $last, $last, substr($idf, 1, -1));
}
-/** Shortcut for $connection->quote($string) */
+/** Shortcut for connection()->quote($string) */
function q(string $string): string {
- global $connection;
- return $connection->quote($string);
+ return connection()->quote($string);
}
/** Escape string to use inside '' */
/** Check if connection has at least the given version
* @param string|float $version required version
* @param string|float $maria_db required MariaDB version
-* @param Db $connection2 defaults to $connection
+* @param Db $connection2 defaults to connection()
*/
function min_version($version, $maria_db = "", Db $connection2 = null): bool {
- global $connection;
if (!$connection2) {
- $connection2 = $connection;
+ $connection2 = connection();
}
$server_info = $connection2->server_info;
if ($maria_db && preg_match('~([\d.]+)-MariaDB~', $server_info, $match)) {
* @return string|false false if error
*/
function get_val(string $query, int $field = 0, ?Db $conn = null) {
- global $connection;
- $conn = (is_object($conn) ? $conn : $connection);
+ $conn = (is_object($conn) ? $conn : connection());
$result = $conn->query($query);
if (!is_object($result)) {
return false;
* @return list<string>
*/
function get_vals(string $query, $column = 0): array {
- global $connection;
$return = array();
- $result = $connection->query($query);
+ $result = connection()->query($query);
if (is_object($result)) {
while ($row = $result->fetch_row()) {
$return[] = $row[$column];
* @return string[]
*/
function get_key_vals(string $query, Db $connection2 = null, bool $set_keys = true): array {
- global $connection;
if (!is_object($connection2)) {
- $connection2 = $connection;
+ $connection2 = connection();
}
$return = array();
$result = $connection2->query($query);
* @return list<string[]> of associative arrays
*/
function get_rows(string $query, Db $connection2 = null, string $error = "<p class='error'>"): array {
- global $connection;
- $conn = (is_object($connection2) ? $connection2 : $connection);
+ $conn = (is_object($connection2) ? $connection2 : connection());
$return = array();
$result = $conn->query($query);
if (is_object($result)) { // can return true
* @param Field[] $fields
*/
function where(array $where, array $fields = array()): string {
- global $connection;
$return = array();
foreach ((array) $where["where"] as $key => $val) {
$key = bracket_escape($key, true); // true - back
: " = " . unconvert_field($field, q($val)))))
; //! enum and set
if (JUSH == "sql" && preg_match('~char|text~', $field_type) && preg_match("~[^ -@]~", $val)) { // not just [a-z] to catch non-ASCII characters
- $return[] = "$column = " . q($val) . " COLLATE " . charset($connection) . "_bin";
+ $return[] = "$column = " . q($val) . " COLLATE " . charset(connection()) . "_bin";
}
}
foreach ((array) $where["null"] as $key) {
* @param bool $redirect
*/
function query_redirect(string $query, ?string $location, string $message, $redirect = true, bool $execute = true, bool $failed = false, string $time = ""): bool {
- global $connection;
if ($execute) {
$start = microtime(true);
- $failed = !$connection->query($query);
+ $failed = !connection()->query($query);
$time = format_time($start);
}
$sql = ($query ? adminer()->messageQuery($query, $time, $failed) : "");
* @return Result|bool
*/
function queries(string $query) {
- global $connection;
if (!Queries::$start) {
Queries::$start = microtime(true);
}
Queries::$queries[] = (preg_match('~;$~', $query) ? "DELIMITER ;;\n$query;\nDELIMITER " : $query) . ";";
- return $connection->query($query);
+ return connection()->query($query);
}
/** Apply command to all array items
* @uses $_POST["tables"]
*/
function search_tables(): void {
- global $connection;
$_GET["where"][0]["val"] = $_POST["query"];
$sep = "<ul>\n";
foreach (table_status('', true) as $table => $table_status) {
$name = adminer()->tableName($table_status);
if (isset($table_status["Engine"]) && $name != "" && (!$_POST["tables"] || in_array($table, $_POST["tables"]))) {
- $result = $connection->query("SELECT" . limit("1 FROM " . table($table), " WHERE " . implode(" AND ", adminer()->selectSearchProcess(fields($table), array())), 1));
+ $result = connection()->query("SELECT" . limit("1 FROM " . table($table), " WHERE " . implode(" AND ", adminer()->selectSearchProcess(fields($table), array())), 1));
if (!$result || $result->fetch_row()) {
$print = "<a href='" . h(ME . "select=" . urlencode($table) . "&where[0][op]=" . urlencode($_GET["where"][0]["op"]) . "&where[0][val]=" . urlencode($_GET["where"][0]["val"])) . "'>$name</a>";
echo "$sep<li>" . ($result ? $print : "<p class='error'>$print: " . error()) . "\n";
echo '<p class="links"><a href="' . h(ME) . 'user=">' . lang('Create user') . "</a>";
-$result = $connection->query("SELECT User, Host FROM mysql." . (DB == "" ? "user" : "db WHERE " . q(DB) . " LIKE Db") . " ORDER BY Host, User");
+$result = connection()->query("SELECT User, Host FROM mysql." . (DB == "" ? "user" : "db WHERE " . q(DB) . " LIKE Db") . " ORDER BY Host, User");
$grant = $result;
if (!$result) {
// list logged user, information_schema.USER_PRIVILEGES lists just the current user too
- $result = $connection->query("SELECT SUBSTRING_INDEX(CURRENT_USER, '@', 1) AS User, SUBSTRING_INDEX(CURRENT_USER, '@', -1) AS Host");
+ $result = connection()->query("SELECT SUBSTRING_INDEX(CURRENT_USER, '@', 1) AS User, SUBSTRING_INDEX(CURRENT_USER, '@', -1) AS Host");
}
echo "<form action=''><p>\n";
json_row("");
} elseif ($_GET["script"] == "kill") {
- $connection->query("KILL " . number($_POST["kill"]));
+ connection()->query("KILL " . number($_POST["kill"]));
} else { // connect
foreach (count_tables(adminer()->databases()) as $db => $val) {
: driver()->update($TABLE, $set, $where_check)
)
);
- $affected = $connection->affected_rows;
+ $affected = connection()->affected_rows;
if (is_object($result)) { // PostgreSQL with RETURNING fills num_rows
$affected += $result->num_rows;
}
if (!$result) {
break;
}
- $affected += $connection->affected_rows;
+ $affected += connection()->affected_rows;
}
}
}
if (!$result) {
break;
}
- $affected += $connection->affected_rows;
+ $affected += connection()->affected_rows;
}
queries_redirect(remove_from_uri(), lang('%d item(s) have been affected.', $affected), $result);
}
}
$start = microtime(true);
//! don't allow changing of character_set_results, convert encoding of displayed query
- if ($connection->multi_query($q) && is_object($connection2) && preg_match("~^$space*+USE\\b~i", $q)) {
+ if (connection()->multi_query($q) && is_object($connection2) && preg_match("~^$space*+USE\\b~i", $q)) {
$connection2->query($q);
}
do {
- $result = $connection->store_result();
+ $result = connection()->store_result();
- if ($connection->error) {
+ if (connection()->error) {
echo ($_POST["only_errors"] ? $print : "");
- echo "<p class='error'>" . lang('Error in query') . ($connection->errno ? " ($connection->errno)" : "") . ": " . error() . "\n";
+ echo "<p class='error'>" . lang('Error in query') . (connection()->errno ? " (" . connection()->errno . ")" : "") . ": " . error() . "\n";
$errors[] = " <a href='#sql-$commands'>$commands</a>";
if ($_POST["error_stops"]) {
break 2;
$time = " <span class='time'>(" . format_time($start) . ")</span>"
. (strlen($q) < 1000 ? " <a href='" . h(ME) . "sql=" . urlencode(trim($q)) . "'>" . lang('Edit') . "</a>" : "") // 1000 - maximum length of encoded URL in IE is 2083 characters
;
- $affected = $connection->affected_rows; // getting warnings overwrites this
+ $affected = connection()->affected_rows; // getting warnings overwrites this
$warnings = ($_POST["only_errors"] ? "" : driver()->warnings());
$warnings_id = "warnings-$commands";
if ($warnings) {
stop_session();
}
if (!$_POST["only_errors"]) {
- echo "<p class='message' title='" . h($connection->info) . "'>" . lang('Query executed OK, %d row(s) affected.', $affected) . "$time\n";
+ echo "<p class='message' title='" . h(connection()->info) . "'>" . lang('Query executed OK, %d row(s) affected.', $affected) . "$time\n";
}
}
echo ($warnings ? "<div id='$warnings_id' class='hidden'>\n$warnings</div>\n" : "");
}
$start = microtime(true);
- } while ($connection->next_result());
+ } while (connection()->next_result());
}
$query = substr($query, $offset);
$grants = array();
$old_pass = "";
-if (isset($_GET["host"]) && ($result = $connection->query("SHOW GRANTS FOR " . q($USER) . "@" . q($_GET["host"])))) { //! use information_schema for MySQL 5 - column names in column privileges are not escaped
+if (isset($_GET["host"]) && ($result = connection()->query("SHOW GRANTS FOR " . q($USER) . "@" . q($_GET["host"])))) { //! use information_schema for MySQL 5 - column names in column privileges are not escaped
while ($row = $result->fetch_row()) {
if (preg_match('~GRANT (.*) ON (.*) TO ~', $row[0], $match) && preg_match_all('~ *([^(,]*[^ ,(])( *\([^)]+\))?~', $match[1], $matches, PREG_SET_ORDER)) { //! escape the part between ON and TO
foreach ($matches as $val) {
if ($created) {
// delete new user in case of an error
- $connection->query("DROP USER $new_user");
+ connection()->query("DROP USER $new_user");
}
}
}
include __DIR__ . "/adminer/include/db.inc.php";
include __DIR__ . "/adminer/include/pdo.inc.php";
include __DIR__ . "/adminer/include/driver.inc.php";
-$connection = (object) array('flavor' => '', 'server_info' => '99'); // used in support()
+Adminer\SqlDb::$instance = (object) array('flavor' => '', 'server_info' => '99'); // used in support()
$features = array("check", "call" => "routine", "dump", "event", "privileges", "procedure" => "routine", "processlist", "routine", "scheme", "sequence", "sql", "status", "trigger", "type", "user" => "privileges", "variables", "view");
$lang_ids = array(); // global variable simplifies usage in a callback function
$file = file_get_contents(__DIR__ . "/$project/index.php");
}
function database() {
- global $connection;
- if ($connection) {
+ if (connection()) {
$databases = adminer()->databases(false);
return (!$databases
? get_val("SELECT SUBSTRING_INDEX(CURRENT_USER, '@', 1)") // username without the database list
}
function dumpData($table, $style, $query) {
- global $connection;
- $result = $connection->query($query, 1); // 1 - MYSQLI_USE_RESULT
+ $result = connection()->query($query, 1); // 1 - MYSQLI_USE_RESULT
if ($result) {
while ($row = $result->fetch_assoc()) {
if ($style == "table") {
<?php
namespace Adminer;
-$connection->select_db(adminer()->database());
+connection()->select_db(adminer()->database());
namespace Adminer;
if ($_GET["script"] == "kill") {
- $connection->query("KILL " . number($_POST["kill"]));
+ connection()->query("KILL " . number($_POST["kill"]));
} elseif (list($table, $id, $name) = adminer()->_foreignColumn(column_foreign_keys($_GET["source"]), $_GET["field"])) { // complete
$limit = 11;
- $result = $connection->query("SELECT $id, $name FROM " . table($table) . " WHERE " . (preg_match('~^[0-9]+$~', $_GET["value"]) ? "$id = $_GET[value] OR " : "") . "$name LIKE " . q("$_GET[value]%") . " ORDER BY 2 LIMIT $limit");
+ $result = connection()->query("SELECT $id, $name FROM " . table($table) . " WHERE " . (preg_match('~^[0-9]+$~', $_GET["value"]) ? "$id = $_GET[value] OR " : "") . "$name LIKE " . q("$_GET[value]%") . " ORDER BY 2 LIMIT $limit");
for ($i=1; ($row = $result->fetch_row()) && $i < $limit; $i++) {
echo "<a href='" . h(ME . "edit=" . urlencode($table) . "&where" . urlencode("[" . bracket_escape(idf_unescape($id)) . "]") . "=" . urlencode($row[0])) . "'>" . h($row[1]) . "</a><br>\n";
}
}
function syntaxHighlighting($tableStatuses) {
- $connection = Adminer\connection();
?>
<style>
@import url(<?php echo $this->root; ?>/lib/codemirror.css);
if (match) {
const modes = {
js: 'application/json',
- sql: 'text/x-<?php echo ($connection->flavor == "maria" ? "mariadb" : "mysql"); ?>',
+ sql: 'text/x-<?php echo (Adminer\connection()->flavor == "maria" ? "mariadb" : "mysql"); ?>',
oracle: 'text/x-sql',
clickhouse: 'text/x-sql',
firebird: 'text/x-sql'
}
function get_databases($flush) {
- $connection = connection();
$result = get_rows('SHOW DATABASES');
$return = array();
}
function table_status($name = "", $fast = false) {
- $connection = connection();
$return = array();
- $tables = get_rows("SELECT name, engine FROM system.tables WHERE database = " . q($connection->_db));
+ $tables = get_rows("SELECT name, engine FROM system.tables WHERE database = " . q(connection()->_db));
foreach ($tables as $table) {
$return[$table['name']] = array(
'Name' => $table['name'],
}
function error() {
- $connection = connection();
- return h($connection->error);
+ return h(connection()->error);
}
function types(): array {
}
function tables_list() {
- $connection = connection();
$query = 'SELECT RDB$RELATION_NAME FROM rdb$relations WHERE rdb$system_flag = 0';
- $result = ibase_query($connection->_link, $query);
+ $result = ibase_query(connection()->_link, $query);
$return = array();
while ($row = ibase_fetch_assoc($result)) {
$return[$row['RDB$RELATION_NAME']] = 'table';
}
function table_status($name = "", $fast = false) {
- $connection = connection();
$return = array();
$data = ($name != "" ? array($name => 1) : tables_list());
foreach ($data as $index => $val) {
}
function fields($table) {
- $connection = connection();
$return = array();
$query = 'SELECT r.RDB$FIELD_NAME AS field_name,
r.RDB$DESCRIPTION AS field_description,
LEFT JOIN RDB$CHARACTER_SETS cset ON f.RDB$CHARACTER_SET_ID = cset.RDB$CHARACTER_SET_ID
WHERE r.RDB$RELATION_NAME = ' . q($table) . '
ORDER BY r.RDB$FIELD_POSITION';
- $result = ibase_query($connection->_link, $query);
+ $result = ibase_query(connection()->_link, $query);
while ($row = ibase_fetch_assoc($result)) {
$return[trim($row['FIELD_NAME'])] = array(
"field" => trim($row["FIELD_NAME"]),
}
function error() {
- $connection = connection();
- return h($connection->error);
+ return h(connection()->error);
}
function types(): array {
}
function alter_indexes($table, $alter) {
- $connection = connection();
foreach ($alter as $val) {
list($type, $name, $set) = $val;
if ($set == "DROP") {
- $return = $connection->_db->command(array("deleteIndexes" => $table, "index" => $name));
+ $return = connection()->_db->command(array("deleteIndexes" => $table, "index" => $name));
} else {
$columns = array();
foreach ($set as $column) {
$column = preg_replace('~ DESC$~', '', $column, 1, $count);
$columns[$column] = ($count ? -1 : 1);
}
- $return = $connection->_db->selectCollection($table)->ensureIndex($columns, array(
+ $return = connection()->_db->selectCollection($table)->ensureIndex($columns, array(
"unique" => ($type == "UNIQUE"),
"name" => $name,
//! "sparse"
));
}
if ($return['errmsg']) {
- $connection->error = $return['errmsg'];
+ connection()->error = $return['errmsg'];
return false;
}
}
public $primary = "itemName()";
private function chunkRequest($ids, $action, $params, $expand = array()) {
- $connection = connection();
foreach (array_chunk($ids, 25) as $chunk) {
$params2 = $params;
foreach ($chunk as $i => $id) {
return false;
}
}
- $connection->affected_rows = count($ids);
+ connection()->affected_rows = count($ids);
return true;
}
}
function select(string $table, array $select, array $where, array $group, array $order = array(), $limit = 1, ?int $page = 0, bool $print = false) {
- $connection = connection();
- $connection->next = $_GET["next"];
+ connection()->next = $_GET["next"];
$return = parent::select($table, $select, $where, $group, $order, $limit, $page, $print);
- $connection->next = 0;
+ connection()->next = 0;
return $return;
}
}
function tables_list() {
- $connection = connection();
$return = array();
foreach (sdb_request_all('ListDomains', 'DomainName') as $table) {
$return[(string) $table] = 'table';
}
- if ($connection->error && defined('Adminer\PAGE_HEADER')) {
+ if (connection()->error && defined('Adminer\PAGE_HEADER')) {
echo "<p class='error'>" . error() . "\n";
}
return $return;
}
function error() {
- $connection = connection();
- return h($connection->error);
+ return h(connection()->error);
}
function information_schema($db) {
}
function sdb_request($action, $params = array()) {
- $connection = connection();
list($host, $params['AWSAccessKeyId'], $secret) = adminer()->credentials();
$params['Action'] = $action;
$params['Timestamp'] = gmdate('Y-m-d\TH:i:s+00:00');
'max_redirects' => 0,
))));
if (!$file) {
- $connection->error = lang('Invalid credentials.');
+ connection()->error = lang('Invalid credentials.');
return false;
}
libxml_use_internal_errors(true);
$xml = simplexml_load_string($file);
if (!$xml) {
$error = libxml_get_last_error();
- $connection->error = $error->message;
+ connection()->error = $error->message;
return false;
}
if ($xml->Errors) {
$error = $xml->Errors->Error;
- $connection->error = "$error->Message ($error->Code)";
+ connection()->error = "$error->Message ($error->Code)";
return false;
}
- $connection->error = '';
+ connection()->error = '';
$tag = $action . "Result";
return ($xml->$tag ?: true);
}
$this->database = true;
echo "{\n";
}
- $connection = Adminer\connection();
- $result = $connection->query($query, 1);
+ $result = Adminer\connection()->query($query, 1);
if ($result) {
echo '"' . addcslashes($table, "\r\n\"\\") . "\": [\n";
$first = true;
function dumpData($table, $style, $query) {
if ($_POST['format'] == 'php') {
- $connection = Adminer\connection();
- $result = $connection->query($query, 1);
+ $result = Adminer\connection()->query($query, 1);
if ($result) {
while ($row = $result->fetch_assoc()) {
$this->output[$table][] = $row;
$this->database = true;
echo "<database name='" . Adminer\h(Adminer\DB) . "'>\n";
}
- $connection = Adminer\connection();
- $result = $connection->query($query, 1);
+ $result = Adminer\connection()->query($query, 1);
if ($result) {
while ($row = $result->fetch_assoc()) {
echo "\t<table name='" . Adminer\h($table) . "'>\n";
}
function selectEmailProcess($where, $foreignKeys) {
- $connection = Adminer\connection();
if ($_POST["email_id"]) {
- $result = $connection->query("SELECT $this->subject, $this->message FROM $this->table WHERE $this->id = " . Adminer\q($_POST["email_id"]));
+ $result = Adminer\connection()->query("SELECT $this->subject, $this->message FROM $this->table WHERE $this->id = " . Adminer\q($_POST["email_id"]));
$row = $result->fetch_row();
$_POST["email_subject"] = $row[0];
$_POST["email_message"] = $row[1];
function login($login, $password) {
if (!$_POST && ($master = &$_SESSION["master"])) {
- $connection = Adminer\connection();
- $connection->query("DO MASTER_POS_WAIT('" . Adminer\q($master['File']) . "', $master[Position])");
+ Adminer\connection()->query("DO MASTER_POS_WAIT('" . Adminer\q($master['File']) . "', $master[Position])");
$master = null;
}
}
function messageQuery($query, $time, $failed = false) {
//! doesn't work with sql.inc.php
- $connection = Adminer\connection();
- $result = $connection->query('SHOW MASTER STATUS');
+ $result = Adminer\connection()->query('SHOW MASTER STATUS');
if ($result) {
Adminer\restart_session();
$_SESSION["master"] = $result->fetch_assoc();
$return = &$translations[$idf];
if ($return === null) {
$return = $idf;
- $connection = Adminer\connection();
- $connection->query("INSERT INTO translation (language_id, idf, translation) VALUES (" . Adminer\q($lang) . ", " . Adminer\q($idf) . ", " . Adminer\q($idf) . ")");
+ Adminer\connection()->query("INSERT INTO translation (language_id, idf, translation) VALUES (" . Adminer\q($lang) . ", " . Adminer\q($idf) . ", " . Adminer\q($idf) . ")");
}
return $return;
}