/** * Do NOT use in code, to be used by database_manager only! * @param string|array $sql query * @param array|null $tablenames an array of xmldb table names affected by this request. * @return bool true * @throws ddl_change_structure_exception A DDL specific exception is thrown for any errors. */ public function change_database_structure($sql, $tablenames = null) { $this->get_manager(); // Includes DDL exceptions classes ;-) if (is_array($sql)) { $sql = implode("\n;\n", $sql); } try { $this->query_start($sql, null, SQL_QUERY_STRUCTURE); $result = $this->mysqli->multi_query($sql); if ($result === false) { $this->query_end(false); } while ($this->mysqli->more_results()) { $result = $this->mysqli->next_result(); if ($result === false) { $this->query_end(false); } } $this->query_end(true); } catch (ddl_change_structure_exception $e) { while (@$this->mysqli->more_results()) { @$this->mysqli->next_result(); } $this->reset_caches($tablenames); throw $e; } $this->reset_caches($tablenames); return true; }
public function executeMulti($sql) { if (!$this->connection) { $this->open(); } $ret = $this->connection->multi_query($sql); if (!$ret) { $errMsg = "Can't Execute Query:" . $sql; $errMsg .= "\n MySQL Message:" . $this->connection->error; throw new \RuntimeException($errMsg); } do { if ($this->connection->errno) { $errMsg = "Can't Execute Query:" . $sql; $errMsg .= "\n MySQL Message:" . $this->connection->error; throw new \RuntimeException($errMsg); } if ($result = $this->connection->store_result()) { $result->free_result(); } if (!$this->connection->more_results()) { break; } } while ($this->connection->next_result()); return $ret; }
/** * Rabota s khranimy`mi protcedurami i funktciiami. * * Vy`polnenie khranimy`kh protcedur i funktcii` cherez metod peregruzki metodov * * @param string $store_procedure_name imia khranimoi` protcedury` * @param array $params spisok parametrov khranimoi` protcedury` * @return array rezul`tat */ public static function Call_Procedure($store_procedure_name, $params = []) { $quotedparams = []; foreach ($params as $param) { array_push($quotedparams, $param === null ? 'NULL' : "'" . self::$DB->real_escape_string($param) . "'"); } $sql = 'CALL ' . $store_procedure_name . '(' . implode(',', $quotedparams) . ');'; /* execute multi query */ if (!self::Query_Real($sql)) { return false; } $results = []; do { if (false != ($result = self::$DB->use_result())) { $rows = []; while (false != ($row = $result->fetch_assoc())) { $rows[] = $row; } $result->close(); $results[] = $rows; } } while (self::$DB->more_results() && self::$DB->next_result()); if (1 < count($results)) { return $results; } else { if (1 < count($results[0])) { return $results[0]; } else { if (1 < count($results[0][0])) { return $results[0][0]; } } } return array_shift($results[0][0]); }
/** * This helper method takes care of prepared statements' "bind_result method * , when the number of variables to pass is unknown. * * @param mysqli_stmt $stmt Equal to the prepared statement object. * * @return array The results of the SQL fetch. */ protected function _dynamicBindResults(mysqli_stmt $stmt) { $parameters = array(); $results = array(); // See http://php.net/manual/en/mysqli-result.fetch-fields.php $mysqlLongType = 252; $shouldStoreResult = false; $meta = $stmt->result_metadata(); // if $meta is false yet sqlstate is true, there's no sql error but the query is // most likely an update/insert/delete which doesn't produce any results if (!$meta && $stmt->sqlstate) { return array(); } $row = array(); while ($field = $meta->fetch_field()) { if ($field->type == $mysqlLongType) { $shouldStoreResult = true; } $row[$field->name] = null; $parameters[] =& $row[$field->name]; } // avoid out of memory bug in php 5.2 and 5.3. Mysqli allocates lot of memory for long* // and blob* types. So to avoid out of memory issues store_result is used // https://github.com/joshcam/PHP-MySQLi-Database-Class/pull/119 if ($shouldStoreResult) { $stmt->store_result(); } call_user_func_array(array($stmt, 'bind_result'), $parameters); $this->totalCount = 0; $this->count = 0; while ($stmt->fetch()) { if ($this->returnType == 'Object') { $x = new stdClass(); foreach ($row as $key => $val) { $x->{$key} = $val; } } else { $x = array(); foreach ($row as $key => $val) { $x[$key] = $val; } } $this->count++; array_push($results, $x); } // stored procedures sometimes can return more then 1 resultset if ($this->_mysqli->more_results()) { $this->_mysqli->next_result(); } if (in_array('SQL_CALC_FOUND_ROWS', $this->_queryOptions)) { $stmt = $this->_mysqli->query('SELECT FOUND_ROWS()'); $totalCount = $stmt->fetch_row(); $this->totalCount = $totalCount[0]; } if ($this->returnType == 'Json') { return json_encode($results); } return $results; }
function InitializeData() { $this->TruncateTables(); $r = $this->Connection->multi_query($this->GetDataSQL()); while ($this->Connection->more_results()) { $this->Connection->next_result(); } }
/** * imports a sql file via mysqli * * @param string $sql * * @return int Number of Sql queries made, -1 if error */ public function import_sql($sql) { //connect via mysqli for easier db import $mysqli = new \mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // Run the SQL $i = 1; if ($mysqli->multi_query($sql)) { do { if ($mysqli->more_results()) { $mysqli->next_result(); $i++; } } while ($mysqli->more_results()); } if ($mysqli->errno) { return -1; } mysqli_close($mysqli); return $i; }
/** * @desc Get only multi query result * * @access public * @return mixed */ public function multi_query_result() { $data = array(); do { if ($this->result = $this->link->store_result()) { $data[] = $this->result->fetch_all($this->fetchMode); $this->result->free(); } } while ($this->link->more_results() && $this->link->next_result()); return $data; }
/** * imports a sql file via mysqli * * @param string $sql * @param \WP_Error $error * * @return int Number of Sql queries made, -1 if error */ public function import_sql($sql, $error) { //connect via mysqli for easier db import $mysqli = new \mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // Run the SQL $i = 1; if ($mysqli->multi_query($sql)) { do { if ($mysqli->more_results()) { $mysqli->next_result(); $i++; } } while ($mysqli->more_results()); } if ($mysqli->errno) { $error->add('sql_import_error', __('<b>Mysqli Error:</b> ' . $mysqli->error, 'search-and-replace')); return -1; } mysqli_close($mysqli); return $i; }
public function init() { $this->load->helper(array('form', 'file', 'url')); $this->load->library(array('form_validation')); $cartPath = dirname(FCPATH); $testConfig = is_writeable($cartPath . '/application/config/'); $testUploads = is_writeable($cartPath . '/uploads/'); $testIntl = class_exists('Locale'); $errors = !$testConfig ? '<div class="alert alert-danger" role="alert">The folder "' . $cartPath . '/application/config" must be writable.</div>' : ''; $errors .= !$testUploads ? '<div class="alert alert-danger" role="alert">The folder "' . $cartPath . '/uploads" must be writable.</div>' : ''; $errors .= !$testIntl ? '<div class="alert alert-danger" role="alert">The PHP_INTL Library is required for GoCart and is not installed on your server. <a href="http://php.net/manual/en/book.intl.php">Read More</a></div>' : ''; $this->form_validation->set_rules('hostname', 'Hostname', 'required'); $this->form_validation->set_rules('database', 'Database Name', 'required'); $this->form_validation->set_rules('username', 'Username', 'required'); $this->form_validation->set_rules('password', 'Password', 'trim|required'); $this->form_validation->set_rules('prefix', 'Database Prefix', 'trim'); if ($this->form_validation->run() == FALSE || $errors != '') { $this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>'); $errors .= validation_errors(); $this->load->view('index', ['errors' => $errors]); } else { $dbCred = $this->input->post(); //test the database mysqli_report(MYSQLI_REPORT_STRICT); try { $db = new mysqli($dbCred['hostname'], $dbCred['username'], $dbCred['password'], $dbCred['database']); } catch (Exception $e) { $errors = '<div class="alert alert-danger" role="alert">There was an error connecting to the database</div>'; $this->load->view('index', ['errors' => $errors]); return; } //create the database file $database = $this->load->view('database', $this->input->post(), true); $myfile = fopen($cartPath . '/application/config/database.php', "w"); fwrite($myfile, $database); fclose($myfile); $sql = str_replace('gc_', $dbCred['prefix'], file_get_contents(FCPATH . 'database.sql')); $db->multi_query($sql); // run the dump while ($db->more_results() && $db->next_result()) { } //run through it //set some basic information in settings $query = "INSERT INTO `{$dbCred['prefix']}settings` (`code`, `setting_key`, `setting`) VALUES\n\t\t\t('gocart', 'theme', 'default'),\n\t\t\t('gocart', 'locale', 'en_US'),\n\t\t\t('gocart', 'currency_iso', 'USD'),\n\t\t\t('gocart', 'new_customer_status', '1'),\n\t\t\t('gocart', 'order_statuses', '{\"Order Placed\":\"Order Placed\",\"Pending\":\"Pending\",\"Processing\":\"Processing\",\"Shipped\":\"Shipped\",\"On Hold\":\"On Hold\",\"Cancelled\":\"Cancelled\",\"Delivered\":\"Delivered\"}'),\n\t\t\t('gocart', 'products_per_page', '24'),\n\t\t\t('gocart', 'default_meta_description', 'Thanks for installing GoCart.'),\n\t\t\t('gocart', 'default_meta_keywords', 'open source, ecommerce'),\n\t\t\t('gocart', 'timezone', 'UTC');"; $db->query($query); $db->close(); $url = dirname((isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']) . '/admin'; header('Location: ' . dirname($url) . '/admin'); } }
/** * Create new databases. */ protected static function createDB() { // Setup DB $m = new \mysqli(ini_get('mysqli.default_host'), ini_get('mysqli.default_user') ?: 'root', ini_get('mysqli.default_pw')); if ($m->connect_error) { throw new \PHPUnit_Framework_SkippedTestError("Failed to connect to mysql: " . $m->connect_error); } $sql = file_get_contents(__DIR__ . '/../../support/db.sql'); if (!$m->multi_query($sql)) { throw new \PHPUnit_Framework_SkippedTestError("Failed to initialise DBs: " . $m->error); } // Make sure everything is executed do { $m->use_result(); } while ($m->more_results() && $m->next_result()); self::$reuse_db = true; }
function execute_query($mysqli, $query) { $bcloseconnection = false; // did we get passed a valid connection (i.e. did the calling function already make the connection to the db for us?) if (!isset($mysqli)) { //echo '<br>execute_query: opening db connection'; $bcloseconnection = true; // Connect to the database $mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); // check connection if (mysqli_connect_errno()) { log_error(sprintf("sql_execute: Connect failed: %s\n", mysqli_connect_error())); return false; } } //echo '<br>query='.$query; // execute the query if ($mysqli->multi_query($query)) { // Setup an incrementing count of the result set; $result_set_id = 0; do { if ($result = $mysqli->store_result()) { $ary_results[$result_set_id] = $result; // Increment the result set $result_set_id++; } } while ($mysqli->more_results() && $mysqli->next_result()); // need to check if we got any resultsets back into the array...if not, the query was probably still valid so return TRUE if (!is_array($ary_results)) { return true; } } else { echo $mysqli->error; //log_error(sprintf("sql_execute: the query '%s' failed to execute due to the following error: '%s'", $query, $mysqli->error)); return false; } // if we had to open the connection, then close it if ($bcloseconnection) { //echo '<br>execute_query: closing db connection'; $mysqli->close(); } return $ary_results; }
/** * This helper method takes care of prepared statements' "bind_result method * , when the number of variables to pass is unknown. * * @param mysqli_stmt $stmt Equal to the prepared statement object. * * @return array The results of the SQL fetch. */ protected function _dynamicBindResults(mysqli_stmt $stmt) { $parameters = array(); $results = array(); $meta = $stmt->result_metadata(); // if $meta is false yet sqlstate is true, there's no sql error but the query is // most likely an update/insert/delete which doesn't produce any results if (!$meta && $stmt->sqlstate) { return array(); } $row = array(); while ($field = $meta->fetch_field()) { $row[$field->name] = null; $parameters[] =& $row[$field->name]; } // avoid out of memory bug in php 5.2 and 5.3 // https://github.com/joshcam/PHP-MySQLi-Database-Class/pull/119 if (version_compare(phpversion(), '5.4', '<')) { $stmt->store_result(); } call_user_func_array(array($stmt, 'bind_result'), $parameters); $this->totalCount = 0; $this->count = 0; while ($stmt->fetch()) { $x = array(); foreach ($row as $key => $val) { $x[$key] = $val; } $this->count++; array_push($results, $x); } // stored procedures sometimes can return more then 1 resultset if ($this->_mysqli->more_results()) { $this->_mysqli->next_result(); } if (in_array('SQL_CALC_FOUND_ROWS', $this->_queryOptions)) { $stmt = $this->_mysqli->query('SELECT FOUND_ROWS()'); $totalCount = $stmt->fetch_row(); $this->totalCount = $totalCount[0]; } return $results; }
/** * Executes multiple queries given in one string within a single request. * * @param string $sql The string with the multiple queries. * @return boolean false if the first statement failed. Otherwise true. */ public function queryMulti($sql) { $result = false; $sql = $this->getSqlWithPrefix($sql); /* * Executing the multiple queries. */ if ($this->conn->multi_query($sql)) { while ($this->conn->more_results()) { /* * If more results are available from the multi_query call we go * to the next result and free its memory usage. */ $this->conn->next_result(); $result = $this->conn->store_result(); if ($result) { $result->free(); } } } return $result; }
public function multi_query($resource) { $Timer = microtime(true); if (parent::multi_query($resource)) { do { if ($result = parent::store_result()) { $result->free(); } $this->queryCount++; if (!parent::more_results()) { break; } } while (parent::next_result()); } $this->SQL[] = $resource; if ($this->errno) { if ($this->exception == true) { throw new Exception("SQL Error: " . $this->error . "<br><br>Query Code: " . $resource); } else { return "SQL Error: " . $this->error; } } }
/** * Run a query on a database object, returning the result * * @param mysqli $databaseObj A database object to run the query on. * @param string $query The query to run. * @return mixed An array of results if query is successful, or null on error. */ private function __runQuery($databaseObj, $query) { $results = array(); if ($databaseObj->multi_query($query)) { do { if ($result = $databaseObj->store_result()) { array_push($results, $result->fetch_all(MYSQLI_ASSOC)); $result->free(); } if (!$databaseObj->more_results()) { break; } $databaseObj->next_result(); } while (true); // If we only ran one query and got one result // just return that if (count($results) == 1) { return $results[0]; } return $results; } else { if ($databaseObj->error) { $this->__logMessage(sprintf('Error: Query - %s failed with message - %s', $query, $databaseObj->error)); } } return null; }
private function getLastUpdateSQL() { global $conf; $mysqli = new mysqli($conf["db_host"], $conf["db_user"], $conf["db_pass"], $conf["db_name"], $conf["db_port"]); $this->pageStart = 0; $this->perPage = 1; $proc = "CALL PLSearch('{$this->searchTerm}', '{$this->statusString}', '{$this->genderString}', '{$this->ageString}', '{$this->hospitalString}', '{$this->incident}', '{$this->sortBy}', {$this->pageStart}, {$this->perPage})"; $res = $mysqli->multi_query("{$proc}; SELECT @allCount;"); $this->lastUpdated = '0001-01-01 01:01:01'; if ($res) { $results = 0; $c = 0; do { if ($result = $mysqli->store_result()) { if ($c == 0) { while ($row = $result->fetch_assoc()) { $this->lastUpdated = $row["updated"]; } } $result->close(); if ($mysqli->more_results()) { $c += 1; } } } while ($mysqli->more_results() && $mysqli->next_result()); } $mysqli->close(); $date = new DateTime($this->lastUpdated); $this->lastUpdated = $date->format('Y-m-d H:i:s'); }
<div class="box-inner"> <div class="boxbar"><h2><?php echo $msg; ?> </h2></div> <div class="boxcontent"> <a href="./install.php">[ BACK ]</a> </div> </div> </div> <?php } else { if (file_exists("./database.sql")) { $db = file_get_contents("./database.sql"); $result = $conn->multi_query($db); while ($conn->more_results()) { $conn->next_result(); $conn->use_result(); } if (!$result) { ?> <div class="box-outer top-box"> <div class="box-inner"> <div class="boxbar"><h2>There was an error when importing database!</h2></div> <div class="boxcontent"> <a href="./install.php">[ BACK ]</a> </div> </div> </div> <?php } else {
$res->net_id = $net_id; $res->full_name = $_SESSION['full_name']; $res->priv_level = $_SESSION['priv_level']; $query = "SELECT user_name FROM summaries WHERE net_id='{$net_id}'; "; $result = $mysqli->query($query); list($user) = $result->fetch_row(); if (empty($user)) { $course_id = $_SESSION['canvas_course_id']; $query = "INSERT INTO summaries (net_id, user_name, course_id) VALUES\n ('{$net_id}','{$res->full_name}', '{$course_id}'); "; $mysqli->query($query); } $query = "SELECT * FROM profiles WHERE net_id='{$net_id}' ORDER BY full_name; "; $query .= "SELECT * FROM connections WHERE net_id='{$net_id}' ORDER BY profile_id1, profile_id2; "; $query .= "SELECT p.net_id, s.user_name, COUNT(*) AS network_size, SUM(same_school) AS agg_school,\n SUM(is_faculty) AS agg_faculty, SUM(same_industry) as agg_industry, SUM(more_senior) as agg_senior,\n SUM(same_level) as agg_level, SUM(more_junior) as agg_junior, SUM(same_gender) AS agg_gender,\n SUM(same_nationality) AS agg_nationality,\n SUM(same_ethnicity) AS agg_ethnicity, SUM(tech_skill) AS agg_tech,\n SUM(finance_skill) AS agg_finance, SUM(ops_skill) AS agg_ops,\n SUM(sales_skill) AS agg_sales, SUM(prod_skill) AS agg_prod,\n SUM(gm_skill) AS agg_gm, SUM(vc_skill) AS agg_vc, SUM(other_skill) AS agg_other,\n SUM(same_skill) AS agg_skill,\n (SELECT COUNT(*) FROM connections c WHERE c.net_id=p.net_id) AS num_connections\n FROM profiles p\n INNER JOIN summaries s\n ON s.net_id=p.net_id\n GROUP BY net_id; "; $mysqli->multi_query($query); if ($mysqli->more_results()) { $mysqli->next_result(); $result = $mysqli->store_result(); $json = array(); while ($row = $result->fetch_assoc()) { $json[] = $row; } $res->profiles = $json; } if ($mysqli->more_results()) { $mysqli->next_result(); $result = $mysqli->store_result(); $json = array(); while ($row = $result->fetch_assoc()) { $json[] = $row; }
/** * Executes a query and shows the data in a formatted in a table (like mysql's default pager) of in multiple tables * (in case of a multi query). * * @param string $query The query. * * @return int The total number of rows in the tables. * * @since 1.0.0 * @api */ public static function executeTable($query) { $row_count = 0; self::multiQuery($query); do { $result = self::$mysqli->store_result(); if (self::$mysqli->errno) { self::mySqlError('mysqli::store_result'); } if ($result) { $columns = []; // Get metadata to array. foreach ($result->fetch_fields() as $str_num => $column) { $columns[$str_num]['header'] = $column->name; $columns[$str_num]['type'] = $column->type; $columns[$str_num]['length'] = max(4, $column->max_length, strlen($column->name)); } // Show the table header. self::executeTableShowHeader($columns); // Show for all rows all columns. while ($row = $result->fetch_row()) { $row_count++; // First row separator. echo '|'; foreach ($row as $i => $value) { self::executeTableShowTableColumn($columns[$i], $value); echo '|'; } echo "\n"; } // Show the table footer. self::executeTableShowFooter($columns); } $continue = self::$mysqli->more_results(); if ($continue) { $tmp = self::$mysqli->next_result(); if ($tmp === false) { self::mySqlError('mysqli::next_result'); } } } while ($continue); return $row_count; }
/** * restoreFromSql * * @param string $sqlfile * * @return boolean false or true */ function restoreFromSql($sqlfile, $type = 'file') { ini_set('memory_limit', '64M'); if ($type == 'file' && !is_file($sqlfile)) { throw new Exception("the {$sqlfile} doesn't exist!"); } $metaFile = str_replace('.sql', '.meta', $sqlfile); $queries = 0; if (is_file($metaFile)) { echo "Using {$metaFile} as metadata.\n"; $fp = fopen($sqlfile, 'rb'); $fpmd = fopen($metaFile, 'r'); while ($offset = fgets($fpmd, 1024)) { $buffer = intval($offset); //reading the size of $oData $query = fread($fp, $buffer); //reading string $oData $queries += 1; if (!@mysql_query($query)) { echo mysql_error() . "\n"; echo "==>" . $query . "<==\n"; } } } else { $queries = NULL; try { $mysqli = new mysqli($this->host, $this->user, $this->passwd, $this->dbName); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; } if ($type == 'file') { $query = file_get_contents($sqlfile); } else { if ($type == 'string') { $query = $sqlfile; } else { return false; } } if (trim($query) == "") { return false; } /* execute multi query */ if ($mysqli->multi_query($query)) { do { /* store first result set */ if ($result = $mysqli->store_result()) { while ($row = $result->fetch_row()) { //printf("%s\n", $row[0]); } $result->free(); } /* print divider */ if ($mysqli->more_results()) { //printf("-----------------\n"); } } while ($mysqli->next_result()); } else { throw new Exception(mysqli_error($mysqli)); } /* close connection */ $mysqli->close(); } catch (Exception $e) { echo $query; echo $e->getMessage(); } } return $queries; }
/** * Отчистка соединения с базой данных. * * Соединение с БД может быть рассинхронизоровано. * Наример, запрос вернул несколько наборов результов, а клиент забрал только * часть из них и пытается выполнить следующий запрос. В такой ситуции сервер возвращает * ошибку и ждет пока ползователь заберет все наборы результатов. * Для решение проблемы необходимо забрать все наборы с сервера, чем и занимается данный метод. * * DB::query() и DB::multiQuery() оставляют соединение с базой "чистым". * Метод будет полезен при использования объекта mysqli, полученного с помощью метода * {@link DB::getMysqli() DB::getMysqli()}. * * @param mixed $result если передан объект mysqli_result, то выполнится его закрытие; */ public static function clearResultset($result = null) { if (is_object($result)) { $result->free(); } while (self::$mysqli->more_results() && self::$mysqli->next_result()) { if ($result = self::$mysqli->use_result()) { $result->free(); } } }
CREATE TEMPORARY TABLE IF NOT EXISTS _cibh_maxnodecount ENGINE=MEMORY AS ( SELECT BlockHeight, MAX(CountNode) MaxCountNode FROM _cibh_nodecount GROUP BY BlockHeight ); SELECT NC.BlockHeight BlockHeight, BlockMNPayee, BlockMNRatio FROM _cibh_maxnodecount MNC, _cibh_nodecount NC WHERE MNC.BlockHeight = NC.BlockHeight AND MNC.MaxCountNode = NC.CountNode; EOT; $sql = sprintf($sql, $blockfrom, $blockto, $testnet); xecho("Executing query....\n"); //echo $sql."\n"; $blockhist = array(); if ($mysqli->multi_query($sql) && $mysqli->more_results() && $mysqli->next_result() && $mysqli->more_results() && $mysqli->next_result() && $mysqli->more_results() && $mysqli->next_result() && $mysqli->more_results() && $mysqli->next_result() && ($result = $mysqli->store_result())) { $update = array(); while ($row = $result->fetch_assoc()) { $update[] = sprintf("(%d,%d,'%s',%.9f)", $testnet, intval($row['BlockHeight']), $row['BlockMNPayee'], floatval($row['BlockMNRatio'])); } xecho(" Done (" . count($update) . " computed)\n"); $sql = "INSERT INTO cmd_info_blocks (BlockTestnet, BlockId, BlockMNPayeeExpected, BlockMNValueRatioExpected) VALUES " . implode(",", $update) . " ON DUPLICATE KEY UPDATE BlockMNPayeeExpected = VALUES(BlockMNPayeeExpected), BlockMNValueRatioExpected = VALUES(BlockMNValueRatioExpected)"; // echo $sql."\n"; xecho("Updating expected values in block database:\n"); if ($result = $mysqli->query($sql)) { xecho(" Done (" . $mysqli->info . ")\n"); } else { xecho(" Error (" . $mysqli->errno . ': ' . $mysqli->error . ")\n"); } } else { xecho(" Failed (" . $mysqli->errno . ": " . $mysqli->error . ")\n");
if (!$server->query("CREATE DATABASE IF NOT EXISTS phpback")) { exit_error("ERROR #6: Could not create database"); } if ($server->select_db('phpback') === FALSE) { exit_error("ERROR #5: Generated database connection error"); } $sql = file_get_contents('database_tables.sql'); if ($server->multi_query($sql) === FALSE) { exit_error("ERROR #4: Couldn't create the tables"); } } do { if ($r = $server->store_result()) { $r->free(); } } while ($server->more_results() && $server->next_result()); $result = $server->query("SELECT id FROM settings WHERE name='title'"); if ($result->num_rows == 1) { if (!@chmod('../install', 0777)) { echo "PLEASE DELETE install/ FOLDER MANUALLY. THEN GO TO yourwebsite.com/feedback/admin/ TO LOG IN."; exit; } unlink('index.php'); unlink('install1.php'); unlink('database_tables.sql'); unlink('index2.php'); unlink('install2.php'); header('Location: ../admin'); exit; } else { $server->query("INSERT INTO users(id,name,email,pass,votes,isadmin,banned) VALUES('','" . $_POST['adminname'] . "','" . $_POST['adminemail'] . "','" . hashPassword($_POST['adminpass']) . "', 20, 3,0)");
public function multi_query($resource) { if (parent::multi_query($resource)) { do { if ($result = parent::store_result()) { $result->free(); } $this->queryCount++; if (!parent::more_results()) { break; } } while (parent::next_result()); } if ($this->errno) { throw new Exception("SQL Error: " . $this->error . "<br><br>Query Code: " . $resource); } }
} $database = $LT_SQL->real_escape_string($_REQUEST['database']); $admin_login = $LT_SQL->real_escape_string($_REQUEST['admin_login']); $admin_password = $LT_SQL->real_escape_string($_REQUEST['admin_password']); $LT_SQL->query("CREATE DATABASE IF NOT EXISTS {$database}") or die("Query failed: " . $LT_SQL->error); $LT_SQL->query("USE {$database}") or die("Query failed: " . $LT_SQL->error); // Create the Database Schema (tables and stored procedures) $LT_SQL->autocommit(FALSE); if ($LT_SQL->multi_query(file_get_contents('include/schema.sql'))) { do { $result = $LT_SQL->store_result(); if ($LT_SQL->errno != 0) { $LT_SQL->rollback(); die("Query failed: " . $LT_SQL->error); } } while ($LT_SQL->more_results() && $LT_SQL->next_result()); $LT_SQL->commit(); } else { $LT_SQL->rollback(); die("Query failed: " . $LT_SQL->error); } // Create an Administrator Account $salt = LT_random_salt(); $hash = LT_hash_password($admin_password, $salt); $query = "CALL create_admin('{$admin_login}', '{$hash}', '{$salt}')"; $LT_SQL->query($query) or die('Query failed: ' . $LT_SQL->error); $LT_SQL->commit(); // Create db_config.php file_put_contents('db_config.php', "<?php\n" . "\t\$LT_SQL = new mysqli('{$location}', '{$username}', '{$password}', '{$database}');\n" . "?>\n"); ?>
* To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ header('Content-Type:application/json'); $OK = true; $db = new mysqli("localhost", "root", "", "Bank"); if ($db->connect_error) { $ok = false; } $fil = file_get_contents('../DAL/Bank.sql'); $res = $db->multi_query($fil); if ($res) { do { if ($result = $db->store_result()) { if ($result == false) { $OK = false; } $result->free(); } $db->more_results(); } while ($db->next_result()); } else { $OK = false; } $db->close(); if ($OK) { echo json_encode("OK"); } else { echo json_encode("Feil"); }
$sql = 'select * from ' . $dbname . '.' . $tablename . ' order by _rowid desc ' . $sqllimitstatement . ';'; $mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME); if ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } // Execute the Query $res = $mysqli->multi_query($sql); // Loop through the return data (if required) $result_set_id = 0; do { if ($result = $mysqli->store_result()) { $ary_results[$result_set_id] = $result; // Increment the result set $result_set_id++; } } while ($mysqli->more_results() && $mysqli->next_result()); // Get the data from the result set. if ($ary_results) { while ($row = $ary_results[0]->fetch_assoc()) { $array[] = $row; } } if (count($array) < 1) { $tabledata = "No Records"; } else { $tabledata = array2table($array); // Will output a table of 600px width } //Verify status and prepare output if ($mysqli->errno == 0) { // Success
} if (!empty($customer['lastName'])) { $lastName = $db->real_escape_string($customer['lastName']); } else { $lastName = NULL; } $multi_query .= "INSERT INTO Customers (NameFirst, NameLast, addressBookId) VALUES ('{$firstName}','{$lastName}','" . $customer['addressBookId'] . "');\n"; if (!empty($clientCompany)) { $multi_query .= "UPDATE Customers SET IsCompany='1',Company='{$clientCompany}' WHERE id=LAST_INSERT_ID() LIMIT 1;\n"; } else { $multi_query .= "UPDATE Customers SET IsCompany='0' WHERE id=LAST_INSERT_ID() LIMIT 1;\n"; } } echo 'SQL Query is ' . number_format(strlen($multi_query) / 1000000, 1) . " MB\n"; $db->multi_query($multi_query); while ($db->more_results()) { $db->next_result(); $db->store_result(); } $multi_query = ''; // run and flush multi_query /* Import client contact information from Apple Address Book */ $address_book = file($pref_address_book); if (!is_array($address_book)) { die("Failure while opening and reading address book file"); } $simple_result = array(); $detailed_result = array(); $vcards = array(); $building_vcard = false; /* For every line in the address book */
if (!$sql) { die("Error opening file: " . $sql_file . "\n"); } $succ = true; if ($mysqli->multi_query($sql)) { do { /* store first result set */ if ($result = $mysqli->store_result()) { while ($row = $result->fetch_row()) { printf("%s\n", $row[0]); } $result->free(); } if ($mysqli->error) { $succ = false; trigger_error($mysqli->error, E_USER_ERROR); } if (!$mysqli->more_results()) { break; } if (!$mysqli->next_result()) { break; } } while (true); } $mysqli->close(); if ($succ) { echo "Tables from " . $sql_file . " imported!" . "\n"; } else { echo "Some error happend!" . "\n"; }
<?php $msqi = new mysqli('localhost', 'my_user', 'my_password', 'my_db'); $sql_str = 'START TRANSACTION; SELECT * FROM (SELECT "Test") as `T1`; COMMIT;'; $msqi->multi_query($sql_str); do { $result = $msqi->store_result(); var_dump($result); } while ($msqi->more_results() && $msqi->next_result());