/** * 执行sql * * @return bool|int */ public function execute() { if (!$this->prepare) { return false; } $res = $this->prepare->execute(); $this->mysql->error = $this->prepare->error; $this->mysql->errno = $this->prepare->errno; if ($res) { $id = $this->prepare->insert_id; $affected_rows = $this->prepare->affected_rows; if ($id) { $this->mysql->insert_id = $id; return $id; } //有时候执行更新操作并没有改变任何数据也认为成功 if ($affected_rows >= 0) { $this->mysql->affected_rows = $affected_rows; return true; } return false; } else { return false; } }
/** * Executes a query that has been previously prepared using the mysqli_prepare() function. * When executed any parameter markers which exist will automatically be replaced with the appropriate data. */ public function execute() { $this->stmt->execute(); if ($this->stmt->error) { $this->errors = true; } }
public function execute() { if (count($this->mbind_params)) { $this->mbind_param_do(); } return parent::execute(); }
/** * 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; }
/** * 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(); }
/** * Executes the query */ private function _execute() { $this->_query->execute(); $this->last_error = $this->_query->error; $this->last_errno = $this->_query->errno; $this->num_rows = $this->_query->num_rows; $this->affected_rows = $this->_query->affected_rows; $this->insert_id = $this->_query->insert_id; }
/** * (non-PHPdoc) * @see PreparedStatement::executePreparedStatement() */ public function executePreparedStatement(array $data, $msg = '') { if (!$this->prepareStatementData($data, !empty($this->stmt) ? $this->stmt->param_count : 0, $msg)) { return false; } $this->preparedStatementResult = null; $res = $this->stmt->execute(); return $this->finishStatement($res, $msg); }
/** * Executes a prepared statement. * * @param array $params OPTIONAL Values to bind to parameter placeholders. * @return bool * @throws Zend_Db_Statement_Mysqli_Exception */ public function _execute(array $params = null) { if (!$this->_stmt) { return false; } // if no params were given as an argument to execute(), // then default to the _bindParam array if ($params === null) { $params = $this->_bindParam; } // send $params as input parameters to the statement if ($params) { array_unshift($params, str_repeat('s', count($params))); call_user_func_array(array($this->_stmt, 'bind_param'), $params); } // execute the statement $retval = $this->_stmt->execute(); if ($retval === false) { /** * @see Zend_Db_Statement_Mysqli_Exception */ require_once 'Zend/Db/Statement/Mysqli/Exception.php'; throw new Zend_Db_Statement_Mysqli_Exception("Mysqli statement execute error : " . $this->_stmt->error); } // retain metadata if ($this->_meta === null) { $this->_meta = $this->_stmt->result_metadata(); if ($this->_stmt->errno) { /** * @see Zend_Db_Statement_Mysqli_Exception */ require_once 'Zend/Db/Statement/Mysqli/Exception.php'; throw new Zend_Db_Statement_Mysqli_Exception("Mysqli statement metadata error: " . $this->_stmt->error); } } // statements that have no result set do not return metadata if ($this->_meta !== false) { // get the column names that will result $this->_keys = array(); foreach ($this->_meta->fetch_fields() as $col) { $this->_keys[] = $this->_adapter->foldCase($col->name); } // set up a binding space for result variables $this->_values = array_fill(0, count($this->_keys), null); // set up references to the result binding space. // just passing $this->_values in the call_user_func_array() // below won't work, you need references. $refs = array(); foreach ($this->_values as $i => &$f) { $refs[$i] =& $f; } $this->_stmt->store_result(); // bind to the result variables call_user_func_array(array($this->_stmt, 'bind_result'), $this->_values); } return $retval; }
/** * @return Result */ public function execute($params = []) { $params = $params ?: $this->params; $sql = $this->sql; if ($params) { $emulatedNamedParameters = false; if (array_values($params) != $params) { $emulatedNamedParameters = true; } if ($emulatedNamedParameters) { $actualParameters = []; $sql = preg_replace_callback('`:(\\w+)`', function ($matches) use(&$actualParameters, $params) { $actualParameters[] = $params[$matches[1]]; return "?"; }, $sql); } else { $actualParameters = $params; } $this->statement = $this->mysqli->prepare($sql); if ($this->statement === false) { throw new \InvalidArgumentException($this->mysqli->error); } foreach ($actualParameters as $parameter) { if (is_int($parameter)) { $this->statement->bind_param('i', $parameter); } else { if (is_double($parameter) || is_float($parameter)) { $this->statement->bind_param('d', $parameter); } else { $this->statement->bind_param('s', $parameter); } } } } else { $this->statement = $this->mysqli->prepare($sql); if ($this->statement === false) { throw new \InvalidArgumentException($this->mysqli->error); } } $this->statement->execute(); }
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."; } } } } }
/** * Execute the prepared statement * * @param array $parameters * @return \Attw\Db\Statement\MySQLiStatement */ public function execute(array $parameters = array()) { if (count($this->bindParam) > 0 || count($parameters) > 0) { $this->bindParamOfMySQLi($parameters); } $this->verifyMySQLiErrorsAndThrowException(); if (!$this->stmt->execute()) { StatementException::mysqliStmtError($this->stmt->error, $this->stmt->errno); } $this->result = $this->stmt->get_result(); return $this; }
/** * Выполняет запрос. * * @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(); } }
/** * 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); }
/** * {@inheritdoc} */ public function execute($params = null) { if (null !== $this->_bindedValues) { if (null !== $params) { if (!$this->_bindValues($params)) { throw new MysqliException($this->_stmt->error, $this->_stmt->errno); } } else { if (!call_user_func_array(array($this->_stmt, 'bind_param'), $this->_bindedValues)) { throw new MysqliException($this->_stmt->error, $this->_stmt->errno); } } } if (!$this->_stmt->execute()) { throw new MysqliException($this->_stmt->error, $this->_stmt->errno); } if (null === $this->_columnNames) { $meta = $this->_stmt->result_metadata(); if (false !== $meta) { $columnNames = array(); foreach ($meta->fetch_fields() as $col) { $columnNames[] = $col->name; } $meta->free(); $this->_columnNames = $columnNames; $this->_rowBindedValues = array_fill(0, count($columnNames), NULL); $refs = array(); foreach ($this->_rowBindedValues as $key => &$value) { $refs[$key] =& $value; } if (!call_user_func_array(array($this->_stmt, 'bind_result'), $refs)) { throw new MysqliException($this->_stmt->error, $this->_stmt->errno); } } else { $this->_columnNames = false; } } // We have a result. if (false !== $this->_columnNames) { $this->_stmt->store_result(); } return true; }
/** * 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; }
/** * Executes a prepared statement. * * @param array $params OPTIONAL values to supply as input to statement parameters * @return void */ public function execute(array $params = array()) { // prepare for mysqli $sql = $this->_joinSql(); $mysqli = $this->_connection->getConnection(); $this->_stmt = $mysqli->prepare($sql); if ($this->_stmt === false || $mysqli->errno) { require_once 'Zend/Db/Statement/Mysqli/Exception.php'; throw new Zend_Db_Statement_Mysqli_Exception("Mysqli prepare error: " . $mysqli->error); } // retain metadata $this->_meta = $this->_stmt->result_metadata(); if ($this->_stmt->errno) { require_once 'Zend/Db/Statement/Mysqli/Exception.php'; throw new Zend_Db_Statement_Mysqli_Exception("Mysqli statement metadata error for SQL = \"{$sql}\": " . $this->_stmt->error); } // statements that have no result set do not return metadata if ($this->_meta !== false) { // get the column names that will result $this->_keys = array(); foreach ($this->_meta->fetch_fields() as $col) { $this->_keys[] = $col->name; } // set up a binding space for result variables $this->_values = array_fill(0, count($this->_keys), null); // set up references to the result binding space. // just passing $this->_values in the call_user_func_array() // below won't work, you need references. $refs = array(); foreach ($this->_values as $i => &$f) { $refs[$i] =& $f; } // bind to the result variables call_user_func_array(array($this->_stmt, 'bind_result'), $this->_values); } // send $params as input parameters to the statement if ($params) { array_unshift($params, str_repeat('s', count($params))); call_user_func_array(array($this->_stmt, 'bind_param'), $params); } // execute the statement $this->_stmt->execute(); }
/** * 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; }
/** * @param $query * @param array $parameters * @return $this * @throws \Exception */ public function execute($query, $parameters = []) { $count = substr_count($query, ';'); if ($count >= 1) { $queries = explode(';', $query); if (count($queries) === $count + 1 || count($queries) === $count) { $this->queryCount = $count; } else { throw new \Exception('confusing_query'); } } else { $query .= ';'; $this->queryCount = 1; } $shouldPrepareQuery = count($parameters) > 0; if ($shouldPrepareQuery) { /** @var \mysqli_stmt $statement */ $this->statement = $this->connection->prepare($query); $types = array_keys($parameters); $this->queryParams = array_values($parameters); $this->bindingArguments = [implode($types)]; foreach ($this->queryParams as $key => $value) { $this->bindingArguments[] =& $this->queryParams[$key]; } if (!call_user_func_array([$this->statement, 'bind_param'], $this->bindingArguments)) { throw new \Exception('Could not bind parameters to MySQL statement'); } $this->lastResults = $this->statement->execute(); } else { $this->lastResults = $this->connection->query($query); } if (!$this->lastResults) { throw new \Exception($this->connection->error); } if ($shouldPrepareQuery && $this->lastResults && isset($this->statement)) { $this->affectedRows = $this->statement->affected_rows; } return $this; }
/** * Bind, Execute * * 1. Prepare SQL * 2. (if provided) Bind untyped parameters * otherwise bind any previously provided typed parameters * 3. Execute * * This method used by SELECT/UPDATE/INSERT/DELETE * * @param null $arr_params * @return array|null|object */ private function process($arr_params = NULL) { if (NULL === $arr_params || is_array($arr_params) && count($arr_params) == 0) { if ($this->str_sql) { if ($this->int_state === self::STATE_BOUND) { // The NAMED parameters have already been bound to this object using bind*() methods $this->str_sql = preg_replace_callback(self::NAMED_PARAM_REGEX, array($this, 'applyNamedParam'), $this->str_sql); $this->prepare(); $this->bindParameters(); } elseif ($this->int_state === self::STATE_INIT) { // The query does not require params (e.g. "SELECT * from tblData") $this->prepare(); } } } else { $this->arr_raw_params = $arr_params; if (!is_array($this->arr_raw_params)) { // Support for single, scalar parameters. $this->str_bind_string = $this->getBindType($this->arr_raw_params); $this->arr_bind_params[] =& $this->arr_raw_params; } elseif ($this->isAssoc($arr_params)) { // Shorthand, NAMED parameters $this->str_sql = preg_replace_callback(self::NAMED_PARAM_REGEX, array($this, 'applyNamedParam'), $this->str_sql); } else { // Shorthand, unnamed (i.e. numerically indexed) - parameters must be passed in the correct order foreach ($this->arr_raw_params as $int_key => $mix_param) { $this->str_bind_string .= $this->getBindType($mix_param); $this->arr_bind_params[] =& $this->arr_raw_params[$int_key]; } } $this->prepare(); $this->bindParameters(); } $this->int_state = self::STATE_EXECUTED; self::$int_execute++; return $this->obj_stmt->execute(); }
/** * 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; }
/** * 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); }
/** * @param mysqli $db * @param mysqli_stmt $stmt * @return boolean The result of mysqli_stmt->execute() */ function checkExecute($db, $stmt) { $result = $stmt->execute(); if ($result === FALSE) { stmtError($db, $stmt); } return $result; }
/** Takes a prepared statement and fetches all objects from it * @param string $className Name of the class contained in table * @return array of objects */ private function RunAndFetchObjects($className, mysqli_stmt $stmt) { $result = $stmt->execute(); $ret = array(); $result = $stmt->get_result(); while ($object = $result->fetch_object()) { //NOTE! requires that we have a pk in the object not that obvious $ret[] = $object; //$ret[$object -> uid] = $object; } $stmt->close(); return $ret; }
// You should also check filesize here. if ($photoFile['size'] > 5242880) { throw new RuntimeException('Exceeded filesize limit.'); } // Check MIME Type by yourself. $finfo = new finfo(FILEINFO_MIME_TYPE); if (false === ($ext = array_search($finfo->file($photoFile['tmp_name']), array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'), true))) { throw new RuntimeException('Invalid file format.'); } $id = -1; $dateNow = date("Y-m-d H:i:s"); $stmt = new mysqli_stmt($mysqli, "INSERT INTO photos (user_id, adv_id, file_ext, date) VALUES (?, ?, ?, ?) "); $success = FALSE; if ($stmt) { $stmt->bind_param("iiss", $_POST['user_id'], $_POST['adv_id'], $ext, $dateNow); if ($stmt->execute()) { $id = $stmt->insert_id; $success = TRUE; } } // On this example, obtain safe unique name from its binary data. if ($success) { if (!move_uploaded_file($photoFile['tmp_name'], sprintf('../img/contents/%s.%s', $id, $ext))) { throw new RuntimeException('Failed to move uploaded file.'); } } else { echo "nothing inserted into db"; } echo 'File is uploaded successfully.'; } catch (RuntimeException $e) { echo $e->getMessage();
/** * Carica un docente eseguendo un prepared statement * @param mysqli_stmt $stmt * @return null */ private function caricaAdminDaStmt(mysqli_stmt $stmt) { if (!$stmt->execute()) { error_log("[caricaAdminDaStmt] impossibile" . " eseguire lo statement"); return null; } $row = array(); $bind = $stmt->bind_result($row['admin_id'], $row['admin_username'], $row['admin_password'], $row['admin_nome'], $row['admin_cognome'], $row['admin_via'], $row['admin_civico'], $row['admin_cap'], $row['admin_citta'], $row['admin_telefono']); if (!$bind) { error_log("[caricaAdminDaStmt] impossibile" . " effettuare il binding in output"); return null; } if (!$stmt->fetch()) { return null; } $stmt->close(); return self::creaAdminDaArray($row); }
function isUserVerified($mysqli, $userID) { $stmt = new mysqli_stmt($mysqli, "SELECT verified FROM users WHERE id = ?"); if ($stmt) { $stmt->bind_param('i', $userID); $stmt->execute(); $result = $stmt->get_result()->fetch_object(); if ($result->verified == TRUE) { return TRUE; } else { return FALSE; } } else { return FALSE; } }
/** * Executes a prepared statement. * * @param array $params OPTIONAL Values to bind to parameter placeholders. * @return bool * @throws coreDatabaseException */ public function _execute(array $params = null) { if (!$this->_stmt) { return false; } // if no params were given as an argument to execute(), // then default to empty array if ($params === null) { $params = array(); } // send $params as input parameters to the statement if ($params) { array_unshift($params, str_repeat('s', count($params))); call_user_func_array(array($this->_stmt, 'bind_param'), $params); } // execute the statement $retval = $this->_stmt->execute(); if ($retval === false) { throw new coreDatabaseException("Mysqli statement execute error : " . $this->_stmt->error); } return $retval; }
<?php require_once "connect.inc"; $mysql = new my_mysqli($host, $user, $passwd, $db, $port, $socket); $stmt = new mysqli_stmt($mysql, "SELECT 'foo' FROM DUAL"); $stmt->execute(); $stmt->bind_result($foo); $stmt->fetch(); $stmt->close(); $mysql->close(); var_dump($foo);
public function &caricaOrdiniDaStmt(mysqli_stmt $stmt) { $ordini = array(); if (!$stmt->execute()) { error_log("[caricaOrdiniDaStmt] impossibile" . " eseguire lo statement"); return null; } $row = array(); $bind = $stmt->bind_result($row['ordine_id'], $row['ordine_domicilio'], $row['ordine_prezzo'], $row['ordine_stato'], $row['ordine_data'], $row['cliente_id'], $row['admin_id']); if (!$bind) { error_log("[caricaOrdiniDaStmt] impossibile" . " effettuare il binding in output"); return null; } while ($stmt->fetch()) { $ordini[] = self::creaOrdineDaArray($row); } $stmt->close(); return $ordini; }
/** * Carica una lista di pagamenti eseguendo un prepared statement * @param mysqli_stmt $stmt * @param $flag : 1 -> un metodo | 2 -> piu' di uno * @return null */ public function caricaPagamentiDaStmt(mysqli_stmt $stmt, $flag = 1) { if (!$stmt->execute()) { error_log("[caricaPagamentiDaStmt] impossibile" . " eseguire lo statement"); return null; } $row = array(); $bind = $stmt->bind_result($row['id'], $row['saldo'], $row['num_carta'], $row['cod_carta'], $row['scadenza_carta'], $row['titolare_carta'], $row['tipo_carta']); if (!$bind) { error_log("[caricaPagamentiDaStmt] impossibile" . " effettuare il binding in output"); return null; } if ($flag == 1) { if (!$stmt->fetch()) { return null; } $stmt->close(); return self::creaPagamentoDaArray($row); } else { $pagamenti = array(); while ($stmt->fetch()) { $pagamenti[] = self::creaPagamentoDaArray($row); } $stmt->close(); return $pagamenti; } }