/** * @param \mysqli_stmt $resource * @param string $column * * @return mixed[] */ protected function fetchResource($resource, $column) { $result = []; $metadata = $resource->result_metadata(); $fields = $metadata->fetch_fields(); if (count($fields) == 0) { return []; } $variables = []; $data = []; foreach ($fields as $field) { $variables[] =& $data[$field->name]; } $resource->bind_result(...$variables); while ($resource->fetch()) { $clone = []; foreach ($data as $key => $value) { $clone[$key] = $value; } $result[] = $clone; } $resource->free_result(); $this->fixTypes($result, $fields, $column); return $result; }
private function doLoginWithPostData() { // check login form contents if (empty($_POST['email'])) { $this->errors[] = "Email field was empty."; } else { if (empty($_POST['password'])) { $this->errors[] = "Password field was empty."; } else { if (!empty($_POST['email']) && !empty($_POST['password'])) { $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // change character set to utf8 and check it if (!$this->db_connection->set_charset("utf8")) { $this->errors[] = $this->db_connection->error; } // if no connection errors (= working database connection) if (!$this->db_connection->connect_errno) { // escape the POST stuff $email = $this->db_connection->real_escape_string($_POST['email']); // database query, getting all the info of the selected user (allows login via email address in the // username field) $sql = new mysqli_stmt($this->db_connection, "SELECT id, first_name, last_name, email, password, privilege FROM users WHERE email = ?;"); $sql->bind_param("s", $_POST['email']); $sql->execute(); $result_of_login_check = $sql->get_result(); // if this user exists if ($result_of_login_check->num_rows == 1) { // get result row (as an object) $result_row = $result_of_login_check->fetch_object(); // using PHP 5.5's password_verify() function to check if the provided password fits // the hash of that user's password if (password_verify($_POST['password'], $result_row->password)) { // write user data into PHP SESSION (a file on your server) $_SESSION['id'] = $result_row->id; $_SESSION['first_name'] = $result_row->first_name; $_SESSION['last_name'] = $result_row->last_name; $_SESSION['email'] = $result_row->email; // $_SESSION['privilege'] = $result_row->privilege; $_SESSION['user_login_status'] = 1; $this->messages[] = "You have logged in successfully!"; } else { $this->errors[] = "Wrong password. Try again."; } } else { $this->errors[] = "This user does not exist."; } } else { $this->errors[] = "Database connection problem."; } } } } }
/** * * 关闭 stmt result mysqli的函数,传入这三个东西就行 * @param mysqli,stmt,result */ static function close(mysqli $mysqli = null, mysqli_stmt $stmt = null, mysqli_result $result = null) { if ($result != null) { $result->free(); } if ($stmt != null) { $stmt->close(); } if ($mysqli != null) { $mysqli->close(); } }
/** * 释放资源 * * @return void */ public function free() { if ($this->prepare instanceof \mysqli_stmt) { $this->prepare->close(); $this->prepare = null; } }
public function preparedStatementClose() { if ($this->stmt) { $this->stmt->close(); $this->stmt = null; } }
/** * Get one row of data * * @return array|null * @access protected */ protected function getOneRow() { if (null === $this->cols) { $result = $this->statement->result_metadata(); if (false === $result) { return false; } $this->cols = []; // set column name foreach ($result->fetch_fields() as $col) { $this->cols[] = $col->name; } // bind values $this->vals = array_fill(0, count($this->cols), null); $refs = []; foreach ($this->vals as $i => &$f) { $refs[$i] =& $f; } call_user_func_array([$this->statement, 'bind_result'], $refs); } if ($this->statement->fetch()) { $row = []; foreach ($this->cols as $i => $col) { $row[$col] = $this->vals[$i]; } return $row; } return false; }
public function execute() { if (count($this->mbind_params)) { $this->mbind_param_do(); } return parent::execute(); }
/** * executar * Recebe os dados, monta o bind_param e executa. * * @param array * @throws Exception */ protected function executar(array $dados) { /** @var array */ $params = $this->prepararDados($dados); /** Passa os paramentros ao bind_param */ if (count($dados) > 0) { if ($this->stmt) { call_user_func_array(array($this->stmt, 'bind_param'), $this->makeValuesReferenced($params)); } else { throw new Exception("Erro ao executar \"{$this->mysqli->error}\"", $this->mysqli->errno); } } /** Executa a consulta e verifica se ocorreu algum erro */ if (!$this->stmt->execute()) { throw new Exception("Erro ao executar: (" . $this->stmt->error . ") ", $this->stmt->errno); } /** Preenche o array de dados caso haja algum retorno */ $this->result = array(); $r = $this->stmt->get_result(); if ($r) { while ($row = $r->fetch_assoc()) { $this->result[] = $row; } } /** Fecha o stamtment e a conexao com o banco */ $this->stmt->close(); $this->mysqli->close(); }
/** * Execute * * @param ParameterContainer $parameters * @return mixed */ public function execute($parameters = null) { if (!$this->isPrepared) { $this->prepare(); } /** START Standard ParameterContainer Merging Block */ if (!$this->parameterContainer instanceof ParameterContainer) { if ($parameters instanceof ParameterContainer) { $this->parameterContainer = $parameters; $parameters = null; } else { $this->parameterContainer = new ParameterContainer(); } } if (is_array($parameters)) { $this->parameterContainer->setFromArray($parameters); } if ($this->parameterContainer->count() > 0) { $this->bindParametersFromContainer(); } /** END Standard ParameterContainer Merging Block */ if ($this->resource->execute() === false) { throw new Exception\RuntimeException($this->resource->error); } if ($this->bufferResults === true) { $this->resource->store_result(); $this->isPrepared = false; $buffered = true; } else { $buffered = false; } $result = $this->driver->createResult($this->resource, $buffered); return $result; }
/** * Fetches a row from the result set. * * @param $style * @param $cursor * @param $offset * @return $data * @throws Zend_Db_Statement_Mysqli_Exception */ public function fetch($style = null, $cursor = null, $offset = null) { // fetch the next result $retval = $this->_stmt->fetch(); switch ($retval) { case null: // end of data // end of data case false: // error occurred $this->closeCursor(); return $retval; default: // fallthrough } // make sure we have a fetch mode if ($style === null) { $style = $this->_fetchMode; } // dereference the result values, otherwise things like fetchAll() // return the same values for every entry (because of the reference). $values = array(); foreach ($this->_values as $key => $val) { $values[] = $val; } // bind back to external references foreach ($this->_bindColumn as $key => &$val) { if (is_integer($key)) { // bind by column position // note that vals are 0-based, but cols are 1-based $val = $values[$key - 1]; } else { // bind by column name $i = array_search($key, $this->_keys); $val = $values[$i]; } } $data = false; switch ($style) { case Zend_Db::FETCH_NUM: $data = $values; break; case Zend_Db::FETCH_ASSOC: $data = array_combine($this->_keys, $values); break; case Zend_Db::FETCH_BOTH: $assoc = array_combine($this->_keys, $values); $data = array_merge($values, $assoc); break; case Zend_Db::FETCH_OBJ: $data = (object) array_combine($this->_keys, $values); break; default: require_once 'Zend/Db/Statement/Mysqli/Exception.php'; throw new Zend_Db_Statement_Mysqli_Exception("Invalid fetch mode specified"); break; } return $data; }
public function store_result() { $retval = $this->statement->store_result(); if (false === $retval) { throw new BeeHub_MySQL(self::mysqli()->error, self::mysqli()->errno); } return $retval; }
/** * Fetches a row from the result set. * * @param int $style OPTIONAL Fetch mode for this fetch operation. * @param int $cursor OPTIONAL Absolute, relative, or other. * @param int $offset OPTIONAL Number for absolute or relative cursors. * @return mixed Array, object, or scalar depending on fetch mode. * @throws Zend_Db_Statement_Mysqli_Exception */ public function fetch($style = null, $cursor = null, $offset = null) { if (!$this->_stmt) { return false; } // fetch the next result $retval = $this->_stmt->fetch(); switch ($retval) { case null: // end of data // end of data case false: // error occurred $this->_stmt->reset(); return $retval; default: // fallthrough } // make sure we have a fetch mode if ($style === null) { $style = $this->_fetchMode; } // dereference the result values, otherwise things like fetchAll() // return the same values for every entry (because of the reference). $values = array(); foreach ($this->_values as $key => $val) { $values[] = $val; } $row = false; switch ($style) { case Zend_Db::FETCH_NUM: $row = $values; break; case Zend_Db::FETCH_ASSOC: $row = array_combine($this->_keys, $values); break; case Zend_Db::FETCH_BOTH: $assoc = array_combine($this->_keys, $values); $row = array_merge($values, $assoc); break; case Zend_Db::FETCH_OBJ: $row = (object) array_combine($this->_keys, $values); break; case Zend_Db::FETCH_BOUND: $assoc = array_combine($this->_keys, $values); $row = array_merge($values, $assoc); return $this->_fetchBound($row); break; default: /** * @see Zend_Db_Statement_Mysqli_Exception */ require_once 'Zend/Db/Statement/Mysqli/Exception.php'; throw new Zend_Db_Statement_Mysqli_Exception("Invalid fetch mode '{$style}' specified"); break; } return $row; }
/** * Carica un indirizzo eseguendo un prepared statement * @param mysqli_stmt $stmt * @return null */ public function caricaIndirizzoDaStmt(mysqli_stmt $stmt) { if (!$stmt->execute()) { error_log("[caricaIndirizzoDaStmt] impossibile" . " eseguire lo statement"); return null; } $row = array(); $bind = $stmt->bind_result($row['id'], $row['destinatario'], $row['via_num'], $row['citta'], $row['provincia'], $row['cap'], $row['telefono']); if (!$bind) { error_log("[caricaIndirizzoDaStmt] impossibile" . " effettuare il binding in output"); return null; } if (!$stmt->fetch()) { return null; } $stmt->close(); return self::creaIndirizzoDaArray($row); }
/** * Carica una lista di articoli eseguendo un prepared statement * @param mysqli_stmt $stmt * @return null */ public function &caricaArticoliDaStmt(mysqli_stmt $stmt) { $articoli = array(); if (!$stmt->execute()) { error_log("[caricaArticoliDaStmt] impossibile" . " eseguire lo statement"); return null; } $row = array(); $bind = $stmt->bind_result($row['id'], $row['size'], $row['qty'], $row['prezzo'], $row['pizza_id']); if (!$bind) { error_log("[caricaArticoliDaStmt] impossibile" . " effettuare il binding in output"); return null; } while ($stmt->fetch()) { $articoli[] = self::creaArticoloDaArray($row); } $stmt->close(); return $articoli; }
/** * Rewind */ public function rewind() { if ($this->position !== 0) { if ($this->isBuffered === false) { throw new Exception\RuntimeException('Unbuffered results cannot be rewound for multiple iterations'); } } $this->resource->data_seek(0); // works for both mysqli_result & mysqli_stmt $this->currentComplete = false; $this->position = 0; }
/** * Load the column metadata from the last query. * @return array */ public function load_col_info() { if ($this->col_info) { return $this->col_info; } $num_fields = $this->result->field_count; for ($i = 0; $i < $num_fields; $i++) { $this->col_info[$i] = $this->result->fetch_field_direct($i); } return $this->col_info; }
/** * Rewind * */ public function rewind() { $this->currentComplete = false; $this->position = 0; if ($this->resource instanceof \mysqli_stmt) { //$this->resource->reset(); } else { $this->resource->data_seek(0); // works for both mysqli_result & mysqli_stmt } }
/** * Method to free up the memory used for the result set. * * @param mixed $cursor The optional result set cursor from which to fetch the row. * * @return void * * @since 1.0 */ protected function freeResult($cursor = null) { $this->executed = false; if ($cursor instanceof \mysqli_result) { $cursor->free_result(); } if ($this->prepared instanceof \mysqli_stmt) { $this->prepared->close(); $this->prepared = null; } }
/** * @return boolean|array */ private function _fetch() { $ret = $this->_stmt->fetch(); if (true === $ret) { $values = array(); foreach ($this->_rowBindedValues as $v) { $values[] = $v; } return $values; } return $ret; }
/** * Clean up all vars */ private function _cleanup() { $this->_select = array(); $this->_target = ""; //$this->_query_string = ""; $this->_where = array(); $this->_bind_params = array(''); $this->_joins = array(); $this->_limit = array(); $this->_orderBy = array(); $this->_query->close(); }
public function nextRecord() { // Skip data if out of data if (!$this->statement->fetch()) { return false; } // Dereferenced row $row = array(); foreach ($this->boundValues as $key => $value) { $row[$key] = $value; } return $row; }
/** * Выполняет запрос. * * @return void */ public function execute() { $types = str_split($this->debugTypes); $params = ['types' => $types, 'vars' => $this->debugVars]; $sql = $this->createSqlString($params); $this->mysqli->autocommit(false); $this->mysqli->query($sql); $this->mysqli->rollback(); if (empty($this->mysqli->error)) { $bindParams = $this->boundParams($params); call_user_func_array(['parent', 'bind_param'], $bindParams); parent::execute(); } }
/** * @return array * @throws \Exception */ public function fetchAll() { $results = [$this->translator->trans('sorry', array(), 'messages'), $this->translator->trans('wrong_query_execution', array(), 'messages')]; do { if (isset($this->connection->field_count) && !$this->connection->field_count) { if (strlen($this->connection->error) > 0) { $error = $this->connection->error; if ($this->connection->errno === 2014) { // Repair all tables of the test database $this->logger->error('[CONNECTION] ' . $error); } else { $this->logger->info('[CONNECTION] ' . $error); } throw new \Exception($error); } else { $this->lastResults = self::RESULTS_NONE; $results[1] = $this->translator->trans('no_record', array(), 'messages'); if (!is_null($this->statement) && $this->statement instanceof \mysqli_stmt) { /** * @see http://stackoverflow.com/a/25377031/2820730 about using \mysqli and xdebug */ $this->statement->close(); unset($this->statement); } } } else { $queryResult = $this->lastResults; /** * @var \mysqli_result $queryResult */ if (is_object($queryResult) && $queryResult instanceof \mysqli_result) { $results = []; while ($result = $queryResult->fetch_array(MYSQLI_ASSOC)) { if (!is_null($result)) { $results[] = $result; } } } } $this->queryCount--; } while ($this->queryCount > 0); return $results; }
public function &creaAlbumDaStmt(mysqli_stmt $stmt) { $album = array(); if (!$stmt->execute()) { error_log("[creaAlbumDaStmt] impossibile" . " eseguire lo statement"); return null; } $row = array(); $bind = $stmt->bind_result($row['id'], $row['nome'], $row['autore'], $row['prezzo']); if (!$bind) { error_log("[creaAlbumDaStmt] impossibile" . " effettuare il binding in output"); return null; } while ($stmt->fetch()) { $album = self::creaAlbumDaArray($row); } $stmt->close(); return $album; }
/** * Get all array data * * @return array */ public function getFetchArrays() { $data = array(); if ($this->resource instanceof \mysqli_result) { $result = $this->resource; } else { if ($this->resource instanceof \mysqli_stmt) { $result = $this->resource->get_result(); } else { if ($this->resource instanceof \mysqli) { $result = $this->resource->store_result(); } } } while ($row = $result->fetch_array(\MYSQLI_ASSOC)) { $data[] = $row; } return $data; }
/** * Execute * * @param ParameterContainer $parameters * @return mixed */ public function execute($parameters = null) { if (!$this->isPrepared) { $this->prepare(); } $parameters = $parameters ?: $this->parameterContainer; if ($parameters != null) { if (is_array($parameters)) { $parameters = new ParameterContainer($parameters); } if (!$parameters instanceof ParameterContainer) { throw new \InvalidArgumentException('ParameterContainer expected'); } $this->bindParametersFromContainer($parameters); } if ($this->resource->execute() === false) { throw new \RuntimeException($this->resource->error); } $result = $this->driver->createResult($this->resource); return $result; }
function executeAndFetch($className = self::DEFAULT_CLASS_NAME, $type = self::RESULT_OBJECT, array $iteratorMap = null) { try { $this->execute(); } catch (\Exception $ex) { throw $ex; } switch ($type) { case self::RESULT_OBJECT: $objectBuilder = $className != self::DEFAULT_CLASS_NAME ? new ObjectBuilderUtil($className) : null; return $this->fetchObject($className, $objectBuilder, $iteratorMap); case self::RESULT_ARRAY: return $this->fetchArray($iteratorMap); default: throw new \InvalidArgumentException('Invalid Return Type'); } $this->stmt->free_result(); if (!$this->reusable) { $this->stmt->close(); unset($this->stmt); } else { $this->stmt->reset(); } }
/** * Execute * * @param null|array|Parameters $parameters * @throws Exception\RuntimeException * @return Result */ public function execute($parameters = null) { if (!$this->isPrepared) { $this->prepare(); } if (!$this->parameters instanceof Parameters) { if ($parameters instanceof Parameters) { $this->parameters = $parameters; $parameters = null; } else { $this->parameters = new Parameters(); } } if (is_array($parameters)) { $this->parameters->setFromArray($parameters); } if ($this->parameters->count() > 0) { $this->bindParameters(); } $return = $this->resource->execute(); if ($return === false) { if (in_array($this->resource->errno, array(1060, 1061, 1062))) { throw new Exception\DuplicateException($this->resource->error, $this->resource->errno); } throw new Exception\RuntimeException($this->resource->error); } if ($this->bufferResults === true) { $this->resource->store_result(); $this->isPrepared = false; $buffered = true; } else { $buffered = false; } $result = $this->driver->createResult($this->resource, $buffered); return $result; }
/** * 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]; } $stmt->store_result(); call_user_func_array(array($stmt, 'bind_result'), $parameters); while ($stmt->fetch()) { $x = array(); foreach ($row as $key => $val) { $x[$key] = $val; } $this->count++; array_push($results, $x); } return $results; }
/** * Carica un cliente eseguendo un prepared statement * @param mysqli_stmt $stmt * @return null */ private function caricaClienteDaStmt(mysqli_stmt $stmt) { if (!$stmt->execute()) { error_log("[caricaClienteDaStmt] impossibile" . " eseguire lo statement"); return null; } $row = array(); $bind = $stmt->bind_result($row['id'], $row['username'], $row['password'], $row['email'], $row['nome'], $row['cognome'], $row['indirizzo']); if (!$bind) { error_log("[caricaClienteDaStmt] impossibile" . " effettuare il binding in output"); return null; } if (!$stmt->fetch()) { return null; } $stmt->close(); return self::creaClienteDaArray($row); }