/** * 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(); } }
/** * @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; }
function makeInstallation($s) { if ($s['createDb']) { /* create BDD */ $mysqli = new mysqli($s['db_adress'], $s['db_user'], $s['db_password']); /* check connection */ if ($mysqli->connect_errno) { printf("Connect failed: %s\n", $mysqli->connect_error); exit(24); } $q = "CREATE DATABASE IF NOT EXISTS `" . $s['db_schema'] . "` /*!40100 DEFAULT CHARACTER SET utf8 */;"; //echo "Création BDD ::".$q; //exit; if (!$mysqli->query($q)) { echo "Création BDD impossible"; exit; } $mysqli->close(); } $mysqli = new mysqli($s['db_adress'], $s['db_user'], $s['db_password'], $s['db_schema']); /* execute multi query */ $mysqli->multi_query(file_get_contents('install/install.sql')); while ($mysqli->next_result()) { } // flush multi_queries /* init de la table des dates de reference */ $start_day = mktime(0, 0, 0, 9, 1, 2014); //1er septembre 2014 $stop_day = mktime(0, 0, 0, 9, 1, 2037); //justqu'au 1er septembre 2037, on verra en 2037 si j'utilise encore l'app. $nb_day = ($stop_day - $start_day) / 86400; $query = "INSERT INTO oko_dateref (jour) VALUES "; for ($i = 0; $i <= $nb_day; $i++) { $day = date('Y-m-d', mktime(0, 0, 0, date("m", $start_day), date("d", $start_day) + $i, date("Y", $start_day))); $query .= "('" . $day . "'),"; } $query = substr($query, 0, strlen($query) - 1) . ";"; //print_r($query);exit; $mysqli->query($query); $mysqli->close(); /* Make Config.php */ $configFile = file_get_contents('config_sample.php'); $configFile = str_replace("###_BDD_IP_###", $s['db_adress'], $configFile); $configFile = str_replace("###_BDD_USER_###", $s['db_user'], $configFile); $configFile = str_replace("###_BDD_PASS_###", $s['db_password'], $configFile); $configFile = str_replace("###_BDD_SCHEMA_###", $s['db_schema'], $configFile); $configFile = str_replace("###_CONTEXT_###", getcwd(), $configFile); $configFile = str_replace("###_TOKEN_###", sha1(rand()), $configFile); //$configFile = str_replace("###_TOKEN-API_###",sha1(rand()),$configFile); file_put_contents('config.php', $configFile); /* Make config.json */ $param = array("chaudiere" => $s['oko_ip'], "tc_ref" => $s['param_tcref'], "poids_pellet" => $s['param_poids_pellet'], "surface_maison" => $s['surface_maison'], "get_data_from_chaudiere" => $s['oko_typeconnect'], "send_to_web" => "0"); file_put_contents('config.json', json_encode($param)); }
/** * Executes a multi query string; typically concatenated by semicolon * @param sring $query * @throws DBExceptions\DatabaseException Raises an exception in case of an error */ public function ExecuteMultiQuery($query) { $result = $this->db->multi_query($query); if ($result) { while ($this->db->next_result()) { } //overgo the results! } if (!$result) { throw new DBExceptions\DatabaseException('Error in multi query', 101, $query); } }
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; }
/** * 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; }
function create_tables($data) { // Connect to the database $mysqli = new mysqli($data['hostname'], $data['db_user'], $data['db_password'], $data['db_name']); // Check for errors if ($mysqli->connect_errno) { $message = "Failed to connect to MySQL: " . $mysqli->connect_error; return false; } // Open the default SQL file $query = file_get_contents('assets/install.sql'); // Execute a multi query if ($mysqli->multi_query($query)) { while ($mysqli->next_result()) { } } // Close the connection $mysqli->close(); return true; }
/** * 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; }
function makeInstallation($s) { if ($s['createDb']) { /* create BDD */ $mysqli = new mysqli($s['db_adress'], $s['db_user'], $s['db_password']); /* check connection */ if ($mysqli->connect_errno) { printf("Connect failed: %s\n", $mysqli->connect_error); exit; } $q = "CREATE DATABASE IF NOT EXISTS `" . $s['db_schema'] . "` /*!40100 DEFAULT CHARACTER SET utf8 */;"; //echo "Création BDD ::".$q; //exit; if (!$mysqli->query($q)) { echo "Création BDD impossible"; exit; } $mysqli->close(); } $mysqli = new mysqli($s['db_adress'], $s['db_user'], $s['db_password'], $s['db_schema']); /* execute multi query */ $mysqli->multi_query(file_get_contents('install/install.sql')); while ($mysqli->next_result()) { } // flush multi_queries $mysqli->close(); /* Make Config.php */ $configFile = file_get_contents('config_sample.php'); $configFile = str_replace("###_BDD_IP_###", $s['db_adress'], $configFile); $configFile = str_replace("###_BDD_USER_###", $s['db_user'], $configFile); $configFile = str_replace("###_BDD_PASS_###", $s['db_password'], $configFile); $configFile = str_replace("###_BDD_SCHEMA_###", $s['db_schema'], $configFile); $configFile = str_replace("###_CONTEXT_###", getcwd(), $configFile); $configFile = str_replace("###_TOKEN_###", sha1(rand()), $configFile); //$configFile = str_replace("###_TOKEN-API_###",sha1(rand()),$configFile); file_put_contents('config.php', $configFile); /* Make config.json */ $param = array("chaudiere" => $s['oko_ip'], "tc_ref" => $s['param_tcref'], "poids_pellet" => $s['param_poids_pellet'], "surface_maison" => $s['surface_maison'], "get_data_from_chaudiere" => $s['oko_typeconnect'], "send_to_web" => "0"); file_put_contents('config.json', json_encode($param)); }
/** * 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; }
<br> <input type="submit" value="Submit"> </form> <?php $mysqli = new mysqli("dbase.cs.jhu.edu", "cs41515_jsham2", "PTIASBIT", "cs41515_jsham2_db"); if (mysqli_connect_errno()) { printf("Connect failed: %s<br>", mysqli_connect_error()); exit; } session_start(); $email = $_SESSION["email_addr"]; if ($mysqli->multi_query("CALL FindFilmsGivenEmail('" . $email . "');")) { printf("<table><tr><th>Film Name</th><th>Year</th><th>Rating</th><th>Genre</th><th>Country</th><th>Language</th><th>Budget</th><th>Gross</th></tr>"); do { if ($result = $mysqli->store_result()) { while ($row = $result->fetch_row()) { printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $row[7]); } $result->close(); } } while ($mysqli->next_result()); printf("</table>"); } else { printf("No results"); } exit; ?> </body> </html>
$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
$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; } $res->connections = $json;
function StoredProcedure2($query="") { //Me conecto a la base de datos $mysqli = new mysqli("atc-nh-natsdb.nationalnet.com", "staffcenter", "XgwofvLY2ayLf", "staffcenter"); /* check connection */ if (mysqli_connect_errno()) { printf("<br />Failed to connect to the database: %s\n", mysqli_connect_error()); exit(); } //LLama al stored procedure if ($mysqli->multi_query($query)) { do { /* guarda el resultado del stored procedure */ if ($result = $mysqli->store_result()) { while ($row = $result->fetch_row()) { $mysqli->kill($mysqli->thread_id); $result->close(); return $row[0]; } } } while ($mysqli->next_result()); } else { echo "<td align=\"center\"><b style=\"font-size:24px\">¡There was an error calling the stored procedure: $mysqli->error</b></font></td>"; } echo "</tr>"; echo "<tr>"; echo "</tr>"; echo "</table>"; $mysqli->kill($mysqli->thread_id); $mysqli->close(); }
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; } } }
public function dowithByLPid($lotyid, $playid) { if (empty($lotyid) || empty($playid)) { $servers = $this->input->server('argv'); $playid = $servers[3]; $lotyid = $servers[2]; } $databasic = array(); $data = array(); //得到玩法下的所有启用状态的自动跟单JOB $all_plan = $this->getAllPlan($lotyid, $playid); foreach ($all_plan as $aplanObj) { $aplan = $aplanObj->as_array(); $auto_roder_jobs = $this->getAllJob($lotyid, $playid, $aplan['user_id']); foreach ($auto_roder_jobs as $aJobObj) { //处理该自动跟单 $ajob = $aJobObj->as_array(); $jobid = $ajob['id']; $uid = $ajob['uid']; $fuid = $ajob['fuid']; switch ($lotyid) { case '1': $pordernum = $aplan['basic_id']; $this->plans_obj = $this->jczq_obj; break; case '2': $pordernum = $aplan['basic_id']; $this->plans_obj = $this->sfc_obj; break; case '6': $pordernum = $aplan['basic_id']; $this->plans_obj = $this->jclq_obj; break; case '7': $pordernum = $aplan['basic_id']; $this->plans_obj = $this->bjdc_obj; break; default: $pordernum = $aplan['order_num']; break; } $pid = $aplan['id']; $iscontinue = $this->log->where(array('pid' => $pid, 'uid' => $uid))->find()->as_array(); if ($iscontinue['id']) { continue; } //竞彩足球 其它彩种还要扩展这里 $result = $this->plans_obj->get_by_order_id($pordernum); switch ($lotyid) { case 2: $result['surplus'] = $result['buyed']; $result['buyed'] = $result['copies'] - $result['surplus']; break; } $errcode = '200'; //验证余额 $userobj = user::get_instance(); $usermoney = $userobj->get_user_money($uid); if ($usermoney < $ajob['money']) { $errcode = '101'; //用户余额不足 } //验证是否满员 if ($result['surplus'] <= 0) { $errcode = '102'; //'此方案已满员无法购买!'; } //验证可认够的钱是否够 if ($result['surplus'] * $result['price_one'] < $ajob['money']) { $errcode = '103'; //方案可购金额小于你的订制金额 } //方案是否限定范围 if ($ajob['limitswitch']) { if ($ajob['maximum'] < $result['total_price']) { $errcode = '104'; //方案金额大于你的限定金额最大值 } if ($ajob['minimum'] > $result['total_price']) { $errcode = '105'; //方案金额小于你的限定金额的最小值 } } //检查方案日期是否结束 if (strtotime($result['time_end']) < time()) { $errcode = '106'; //'此方案已到期无法购买!'; } //检查是否是合买对象 if (!empty($result['friends']) && $result['friends'] != 'all') { $errcode = '107'; //'此方案只有固定的彩友可以合买!'; } $config = Kohana::config('database.default'); extract($config['connection']); $mysqli = new mysqli($host, $user, $pass, $database, $port); if (mysqli_connect_errno()) { echo '数据异常!'; } $mysqli->query("SET NAMES 'utf8'"); if ($errcode == '200') { // echo 'ssss'; $query = "call auto_order('" . $jobid . "','" . $pid . "','" . $lotyid . "','" . $playid . "')"; //echo $query; if ($mysqli->multi_query($query)) { do { if ($rest = $mysqli->store_result()) { while ($row = $rest->fetch_row()) { if ($row[0] != '200') { $sql = "INSERT INTO `auto_order_logs` (`lotyid`,`playid`, `fuid`, `funame`, `uid`, `uname`, `rgmoney`, `state`,\r\n\t\t\t\t\t`isuccess`, `errcode`,\t`ctime`, `ordernum`, `pid`)\r\n\t\t\t\t\tVALUES\t('" . $lotyid . "', '" . $playid . "','" . $fuid . "','" . $ajob['funame'] . "','" . $uid . "','" . $ajob['uname'] . "',0, '1','0', '" . $errcode . "',NOW(), '" . $pordernum . "', " . $pid . ");"; $mysqli->query($sql); } else { if ($row[1] == 100) { //扯分彩票存入彩票表,打印彩票的格式/更新状态 $this->plans_obj->get_tickets($pid, $result['play_method'], $result['codes'], $result['typename'], $result['special_num'], $result['rate'], $result['basic_id']); //更新方案状态为未出票(是父类的方案) $this->plans_obj->update_status($pid, 1); } } } $rest->close(); } } while ($mysqli->next_result()); } } else { $sql = "INSERT INTO `auto_order_logs` (`lotyid`,`playid`, `fuid`, `funame`, `uid`, `uname`, `rgmoney`, `state`,\r\n\t\t\t\t\t`isuccess`, `errcode`,\t`ctime`, `ordernum`, `pid`)\r\n\t\t\t\t\tVALUES\t('" . $lotyid . "', '" . $playid . "','" . $fuid . "','" . $ajob['funame'] . "','" . $uid . "','" . $ajob['uname'] . "',0, '1','0', '" . $errcode . "',NOW(), '" . $pordernum . "', " . $pid . ");"; //echo $sql; $mysqli->query($sql); } } } }
function batch_query($server_cfg, $game_cfg, $queries) { $combined_query = implode(";", $queries); error_log($combined_query . "\n", 3, sprintf($server_cfg['log_file'], $game_cfg['name'])); try { $db = new mysqli($game_cfg["db_host"], $game_cfg["db_user"], $game_cfg["db_pass"], $game_cfg["db_name"]); if (!$db->multi_query(implode(";", $queries))) { error_log("Failed!", 3, sprintf($server_cfg['log_file'], $game_cfg['name'])); $db->close(); return 1; } do { if ($result = $db->store_result()) { while ($row = $result->fetch_row()) { printf("%s\n", $row[0]); } $result->free(); } } while ($db->next_result()); if ($db->errno) { error_log("Stopped while retrieving result : ", 3, sprintf($server_cfg['log_file'], $game_cfg['name'])); $db->close(); return 1; } $db->close(); } catch (Exception $e) { error_log("Error in setting up mysqli multi-query:" . $e->getMessage() . " \n", 3, sprintf($server_cfg['log_file'], $game_cfg['name'])); return 1; } return 0; }
/** * 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; }
/** * get array of multiple results * * returns multi-dimensional array * first dimension is number * from second on the values * * if nothing is provided use assocciative results * */ function getMultipleResults($query) { /* execute query */ $result = parent::multi_query($query); /** * get results to array * first save it, than get each row from result and store it to active[] */ do { $results = parent::store_result(); /* save each to array (only first field) */ while ($row = $results->fetch_row()) { $rows[] = $row[0]; } $results->free(); } while (parent::next_result()); /* return result array of rows */ return $rows; /* free result */ $result->close(); }
</div> <div class='messageinfo'> <p>{$row->messageDate} av: {$row->name}</p> </div> </div> <div class='clear'></div> <hr class='separator' /> <hr class='separator' /> EOD; $res->close(); // ------------------------------------------------------------------------------------------- // // Show the results of NEXT the query // ($mysqli->next_result() && $res = $mysqli->store_result()) or die("Failed to retrieve result from query"); $numRows = $res->num_rows; if($numRows != 0) { $messages .= "<p>Det här inlägget har {$numRows} kommentarer</p>"; } while($row = $res->fetch_object()) { if($user!="") { $commentDelete = $user."&commentId={$row->id}'>Ta bort</a>"; } else { $commentDelete = ""; }
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 printDSS($id, $year) { $config = new Config(); $mysqli = new mysqli($config->host, $config->user, $config->pass, $config->db); if ($mysqli->connect_errno) { print json_encode(array('success' => false, 'status' => 400, 'msg' => 'Failed to connect to MySQL: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error)); return; } else { $data = array(); if (strlen($id) == 2) { $var = str_split($id); $query1 = "SET @rank=0; SELECT A.* ,@rank:=@rank+1 AS rank FROM (SELECT l.id,l.name,l.description,l.landarea,(SELECT COUNT(c.id) FROM child c WHERE c.status_id IN ('{$var['0']}','{$var['1']}') AND c.locationID=l.id AND c.year_id={$year}) AS Count FROM location l GROUP BY l.id ORDER BY Count DESC) AS A WHERE A.Count > 0 LIMIT 5;"; if ($result1 = $mysqli->multi_query($query1)) { do { if ($result1 = $mysqli->store_result()) { while ($row = $result1->fetch_array(MYSQLI_ASSOC)) { array_push($data, $row); } $result1->free(); } } while ($mysqli->next_result()); } return print json_encode(array('success' => true, 'status' => 200, 'data' => $data), JSON_PRETTY_PRINT); } else { $query1 = "CALL printDSS({$id},{$year})"; $result1 = $mysqli->query($query1); while ($row = $result1->fetch_array(MYSQLI_ASSOC)) { array_push($data, $row); } return print json_encode(array('success' => true, 'status' => 200, 'data' => $data), JSON_PRETTY_PRINT); } } }
/** * Execute multiple querries! * */ function executeMultipleQuerries($query, $lastId = false) { # execute querries //$result = parent::multi_query($query); if ($result = parent::multi_query($query)) { do { /* store first result set */ if ($result = parent::store_result()) { $result->free(); } } while (parent::next_result()); } # save lastid $this->lastSqlId = $this->insert_id; # if it failes throw new exception if (mysqli_error($this)) { throw new exception(mysqli_error($this), mysqli_errno($this)); } else { if ($lastId) { return $this->lastSqlId; } else { return true; } } }