/** * 执行sql查询 * * @param string sql语句 * @param array 参数数组 * @param string 返回结果绑定到的对象 * @param boolean 是否输出调试语句 * @return void */ public function query($sql, $params = array(), $class = 'stdClass', $debug = FALSE) { // 预处理绑定语句 try { $this->stmt = $this->db->prepare($sql); if (!$this->stmt) { \core\Handler::appException('pdo prepare error with:' . $sql); throw new \Exception("system error", '49903'); } // 参数绑定 !$params or $this->bindValue($params); // 输出调试 !$debug or $this->debug($sql, $params); // 执行一条sql语句 if ($this->stmt->execute()) { // 设置解析模式 $this->stmt->setFetchMode(\PDO::FETCH_CLASS, $class); } else { throw new \Exception('system error', '49904'); // 获取数据库错误信息 \core\Handler::appException($this->stmt->errorInfo()[2]); } } catch (\Exception $e) { \core\Handler::appException($e->getMessage()); throw new \Exception('system error', '49902'); } }
public function execute($parameters = []) { if ($parameters) { return $this->statement->execute($parameters); } else { return $this->statement->execute(); } }
/** * Create instance. * * @return object */ public static function instance() { if (!isset(self::$instance)) { self::$instance = new self(); self::$instance->setup_constants(); self::$instance->includes(); self::$instance->add_hooks(); self::$instance->execute(); } return self::$instance; }
/** * Prepares a statement and executes the statement using the given query and parameters * @param string $sql A string of the sql query * @param array $params An array of the parameter * @todo Add proper exception handling * @since version 2.0 * @static */ public static function execute($sql, $params = array()) { /* clear stmt */ self::$stmt = ""; try { self::$stmt = self::DBi()->prepare($sql); return self::$stmt->execute($params) ? true : false; } catch (PDOException $e) { return self::pdoException($e); } }
public function executeRedirectTask() { // Joomla 2.5 Backward Compatibility if (version_compare(JVERSION, '3.0', '<')) { $task = JRequest::getCmd('task'); } else { $app = Factory::getApplication(); $task = $app->input->getCmd('task'); } $this->controller->execute($task); $this->controller->redirect(); }
/** * Set the statement object and the pages information * * @param PDOStatement object * @param $pages * @return void */ public function __construct($statement, $pages = '') { if (get_class($statement) != 'PDOStatement') { throw new Exception('PDOStatement expected from this query: ' . Load::factory('Db')->last_sql, 1); } if (in_array('URI', Tk::$lib)) { self::$URI = Load::factory('URI'); } $this->statement = $statement; unset($statement); $this->statement->execute(); $this->pages = $pages; }
/** * SQL query method used to insert buoy data. * * @access private * @param string $buoy_id Station ID number * @param integer $wind_dir Wind direction reading * @param float $wind_spd Wind speed reading * @param float $wave_height Wave height reading * @param float $water_temp Water temperature reading * @param integer $time Time of reading * @return boolean Successful insert query */ function insertBuoyData($buoy_id, $wind_dir, $wind_spd, $wave_height, $water_temp, $time) { $sql = "INSERT INTO\n\t\t\t\t\t" . $this->_tbl . " (\n\t\t\t\t\t\tbuoy_id,\n\t\t\t\t\t\twind_dir,\n\t\t\t\t\t\twind_spd,\n\t\t\t\t\t\twave_height,\n\t\t\t\t\t\twater_temp,\n\t\t\t\t\t\treading_time,\n\t\t\t\t\t\tinsert_stamp\n\t\t\t\t\t) VALUES (\n\t\t\t\t\t\t?, ?, ?, ?, ?, ?, ?\n\t\t\t\t\t)"; $sth = $this->_db->prepare($sql); if (DB::isError($sth)) { exit($sth->getMessage() . ": " . __FILE__ . ": " . __LINE__); } $data = array($buoy_id, $wind_dir, $wind_spd, $wave_height, $water_temp, $time, time()); $res = $this->_db->execute($sth, $data); if (DB::isError($res)) { exit($res->getDebugInfo() . ": " . __FILE__ . ": " . __LINE__); } return true; }
/** * Save a device (add or edit) to the backend. * * @param string $account The account in which this device is valid * @param string $devid Device ID to save * @param array $details Array of device details */ public function saveDevice($account, $devid, &$details) { // Check permissions and possibly update the authentication tokens parent::saveDevice($account, $devid, $details); // See getDevices() for an explanation of these conversions $details['alias'] = $details['name']; $details['name'] = $details['devid']; unset($details['devid']); $details['mailbox'] .= '@' . $account; // Prepare the SQL query and arguments $args = array($details['name'], $account, $details['callerid'], $details['mailbox'], $details['password'], $account, $details['alias']); if (!empty($devid)) { // This is an edit $details['name'] = $details['devid']; $sql = 'UPDATE %s SET name = ?, accountcode = ?, callerid = ?, ' . 'mailbox = ?, secret = ?, context = ?, alias = ?, ' . 'canreinvite = "no", nat = "yes", type = "peer", ' . 'host = "dynamic" WHERE name = ?'; $args[] = $devid; } else { // This is an add. Generate a new unique ID and secret $sql = 'INSERT INTO %s (name, accountcode, callerid, mailbox, ' . 'secret, context, alias, canreinvite, nat, type, host) ' . 'VALUES (?, ?, ?, ?, ?, ?, ?, "no", "yes", "peer", ' . '"dynamic")'; } $sql = sprintf($sql, $this->_params['table']); $msg = 'SQL query in Shout_Driver_Sql#saveDevice(): ' . $sql; Horde::log($msg, 'DEBUG'); $sth = $this->_write_db->prepare($sql); $result = $this->_write_db->execute($sth, $args); if ($result instanceof PEAR_Error) { $msg = $result->getMessage() . ': ' . $result->getDebugInfo(); Horde::log($msg, 'ERR'); throw new Shout_Exception(_("Internal database error. Details have been logged for the administrator.")); } return true; }
/** * adds attributres values to an before created table antry * * @return void * @access private */ private function updateEntity($columns, $values) { $where_clause = "id = " . $this->entity_id; $handler = $this->db->autoPrepare($this->current_entity, $columns, DB_AUTOQUERY_UPDATE, $where_clause); $res = $this->db->execute($handler, $values); $this->handleDbError($res); }
/** * 执行SQL * * @param string $sSQL * @param array $aParam * @param boolean $bStrictMaster * @param boolean $bIsADU * @return unknown */ protected function _exectue($sSQL, $aParam, $bStrictMaster, $bIsADU = false) { $iStartTime = microtime(true); ++self::$_iQueryCnt; self::$_aSQLs[] = $this->_sLastSQL = $sSQL; $db = $bStrictMaster ? $this->_getMasterDB() : $this->_getSlaveDB(); $this->_oSth = $db->prepare($sSQL); if (!empty($aParam)) { $this->_bindParams($aParam); } $bRet = $this->_oSth->execute(); if (false === $bRet) { $sMsg = 'SQL Error: ' . $this->_formatSQL($sSQL, $aParam) . "\n"; $sMsg .= join("\n", $this->_oSth->errorInfo()); throw new Exception($sMsg); return 0; } $iUseTime = round((microtime(true) - $iStartTime) * 1000, 2); self::$_iUseTime += $iUseTime; $iAffectedRows = $this->_oSth->rowCount(); if ($this->_oDebug) { $this->_oDebug->debug('[DB->' . $this->_sDbName . ']: ' . $this->_formatSQL($sSQL, $aParam) . ' AffectedRows:' . $iAffectedRows . ' Use Time:' . $iUseTime . '毫秒'); } // 记录增删改日志 if ($bIsADU) { self::_addADUSQL('[DB->' . $this->_sDbName . ']: ' . $this->_formatSQL($sSQL, $aParam) . ' AffectedRows:' . $iAffectedRows . ' Use Time:' . $iUseTime . '毫秒'); } if ($iAffectedRows > 0 && $bIsADU) { $this->clearWhereCache(); } return $iAffectedRows; }
/** * execute(void) * * Continues the execution of the query after binding params * * @access public * @return void */ public function execute() { $this->pdos->execute(); $this->resultset = $this->pdos; /* * Get the total results with FOUND_ROWS() */ $pdos_fr = $this->options['db_handle']->prepare("SELECT FOUND_ROWS();"); $pdos_fr->execute(); $pdos_fr_result = $pdos_fr->fetch(PDO::FETCH_ASSOC); $this->total_results = $pdos_fr_result['FOUND_ROWS()']; /* * Calculate the total number of pages */ $this->calculate_number_of_pages(); /* * Work out the total number of pages before an ellipses is shown */ $this->calculate_max_pages_before_ellipses(); /* * Build the HTML to output */ $this->build_links(); /* * Set success to true */ $this->success = true; }
/** * @brief Méthode qui modifie le contenu d'un utilisateur * @param integer $idUtilisateur * @param string $nomUsager * @param string $motPasse * @param string $prenom * @param string $nom * @param string $courriel * @param string $descriptionProfil * @param string $photoProfil * @param string $administrateur * @access public * @return void */ public function modifierUtilisateur($motPasse, $prenom, $nom, $descriptionProfil, $idUtilisateur) { $msgErreurs = $this->validerFormUtilisateur($prenom, $nom, $descriptionProfil); //Validation des champs obligatoires. if ($msgErreurs === null) { return $msgErreurs; //Retourne le/les message(s) d'erreur de la validation. } else { try { if ($motPasse == "") { // return "test2"; self::$database->query('UPDATE utilisateurs SET prenom= :prenom, nom= :nom, descriptionProfil= :descriptionProfil WHERE idUtilisateur = :idUtilisateur'); self::$database->bind(':prenom', $prenom); self::$database->bind(':nom', $nom); self::$database->bind(':descriptionProfil', $descriptionProfil); self::$database->bind(':idUtilisateur', $idUtilisateur); } else { self::$database->query('UPDATE utilisateurs SET motPasse= :motPasse, prenom= :prenom, nom= :nom, descriptionProfil= :descriptionProfil WHERE idUtilisateur = :idUtilisateur'); self::$database->bind(':motPasse', $motPasse); self::$database->bind(':prenom', $prenom); self::$database->bind(':nom', $nom); self::$database->bind(':descriptionProfil', $descriptionProfil); self::$database->bind(':idUtilisateur', $idUtilisateur); } self::$database->execute(); } catch (Exception $e) { $msgErreurs["errRequeteModif"] = $e->getMessage(); } } return $msgErreurs; //array vide = succès. }
/** * Inserts $message to the currently open database. Calls open(), * if necessary. Also passes the message along to any Log_observer * instances that are observing this Log. * * @param mixed $message String or object containing the message to log. * @param string $priority The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /* If the connection isn't open and can't be opened, return failure. */ if (!$this->_opened && !$this->open()) { return false; } /* If we don't already have our statement object yet, create it. */ if (!is_object($this->_statement) && !$this->_prepareStatement()) { return false; } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); /* Build our set of values for this log entry. */ $id = $this->_db->nextId($this->_sequence); $values = array($id, $this->_ident, $priority, $message); /* Execute the SQL query for this log entry insertion. */ $result =& $this->_db->execute($this->_statement, $values); if (DB::isError($result)) { return false; } $this->_announce(array('priority' => $priority, 'message' => $message)); return true; }
/** * Fetch the topic participants * * @access public * @param int Topic ID * @param boolean Load and parse member data (TRUE for yes, FALSE for no) * @return array Array of member data indexed by member ID */ public function fetchTopicParticipants($topicID, $parseThem = FALSE) { //----------------------------------------- // INIT //----------------------------------------- $memberData = array(); $remapData = array(); //----------------------------------------- // Grab 'em //----------------------------------------- $this->DB->build(array('select' => '*', 'from' => 'message_topic_user_map', 'where' => 'map_topic_id=' . intval($topicID))); $this->DB->execute(); while ($row = $this->DB->fetch()) { $remapData[$row['map_user_id']] = $row; } if (!count($remapData)) { return array(); } /* Parse 'em? */ if ($parseThem === TRUE) { /* Grab member data */ $memberData = IPSMember::load(array_keys($remapData), 'all'); foreach ($memberData as $id => $data) { $data['_canBeBlocked'] = IPSMember::isIgnorable($data['member_group_id'], $data['mgroup_others']); $memberData[$id] = IPSMember::buildDisplayData($data, array('__all__' => 1)); $memberData[$id] = array_merge($memberData[$id], $remapData[$id]); } $remapData = $memberData; } return $remapData; }
/** * Execute javascript on the database * * @param mixed $code MongoCode or javascript string * @param array $arguments function arguments * * @return mixed result */ public function executeCode($code, array $arguments = []) { if (!$code instanceof MongoCode) { $code = new MongoCode($code); } return $this->database->execute($code, $arguments); }
/** * Starts the framework. */ public function _start() { $dispatched = false; // Flush any existing output if (ob_get_length() > 0) { $this->response()->write(ob_get_contents()); } // Enable output buffering ob_start(); // Enable error handling $this->handleErrors($this->get('flight.handle_errors')); // Disable caching for AJAX requests if ($this->request()->ajax) { $this->response()->cache(false); } // Allow post-filters to run $this->after('start', array($this, 'stop')); // Route the request while ($route = $this->router()->route($this->request())) { $params = array_values($route->params); $continue = $this->dispatcher->execute($route->callback, $params); $dispatched = true; if (!$continue) { break; } $this->router()->next(); } if (!$dispatched) { $this->notFound(); } }
/** * @param $query - string, with params representation instead variables. * @param $param1, param2 .. paramN - variables. * * * example: * ---------------------------------------------------------------------------------- * $param1 = 1; * $param2 = 'cat is very lovelly animal'; * // note that variable in query MUST be in format :1, :2, :3 (and so on). * $query = 'SELECT something FROM tabele WHERE field1=:1 AND field2=:2'; * * multiVariableQuery($query, $param1, $param2 ) * ---------------------------------------------------------------------------------- * * @return true, if the query succeeded; false, if there was SQL error */ public function multiVariableQuery($query) { $numargs = func_num_args(); $arg_list = func_get_args(); if ($numargs === 2 && is_array($arg_list[1])) { // params were passed in array $arg_list = $arg_list[1]; $numargs = count($arg_list) + 1; } try { $this->dbData = $this->dbh->prepare($query); for ($i = 1; $i < $numargs; $i++) { // if ($this->debug) echo 'db.php, # ' . __line__ .". Argument $i is: " . $arg_list[$i] . "<br />\n"; $this->dbData->bindParam(self::bindChar . $i, $arg_list[$i]); } $this->dbData->setFetchMode(PDO::FETCH_ASSOC); $this->dbData->execute(); $this->lastInsertId = $this->dbh->lastInsertId(); } catch (PDOException $e) { $message = $this->errorMessage(__LINE__, $e, $query, $arg_list); if ($this->debug) { self::debugOut($message); } else { self::errorMail($message); } return false; } if ($this->debug) { self::debugOut('db.php, # ' . __LINE__ . ', Query on input: ' . $query . '<br />'); for ($i = 1; $i < $numargs; $i++) { self::debugOut("Param :" . $i . " = " . $arg_list[$i] . "<br>"); } } return true; }
/** * Build the in-memory information tiers * * @access protected * @return @e void */ protected function _buildTiers() { if (!count($this->_itemCache)) { //----------------------------------------- // See if there is a specialized function // for this first //----------------------------------------- if (method_exists($this, $this->_customBuildMethod)) { $method = $this->_customBuildMethod; $this->{$method}(); return; } //----------------------------------------- // Get pages from db //----------------------------------------- $this->_sqlOrder = $this->_sqlOrder ? $this->_sqlOrder : $this->_sqlTitle; $this->DB->build(array('select' => $this->_sqlSelect, 'where' => $this->_sqlWhere, 'from' => $this->_sqlTable, 'order' => $this->_sqlOrder)); $this->DB->execute(); while ($item = $this->DB->fetch()) { if ($item[$this->_sqlParentID] < 1) { $item[$this->_sqlParentID] = 'root'; } $this->_itemCache[$item[$this->_sqlParentID]][$item[$this->_sqlPrimaryID]] = $item; $this->_itemByID[$item[$this->_sqlPrimaryID]] = $item[$this->_sqlParentID]; } } }
/** * - prepare the SQL statement for execution * - binds the parameters through PDO object * - executes the SQL * * @param string the SQL * array parameters to be injected into the SQL statement * @return object current object */ protected function prepare($sql, $args = array()) { $this->statement = $this->connector->prepare($sql); if (!empty($args)) { foreach ($args as $key => $value) { $this->statement->bindParam(':' . $key, $value); } } // if try { $this->statement->execute(); } catch (\PDOException $e) { $this->executionError = $e; } // catch return $this; }
/** This method executes the prepared query @access public @throws PDOException object @return void */ public function execute() { try { return $this->Stmt->execute(); } catch (PDOException $e) { throw $e; } }
protected function execute($handle, $args = array()) { $start = microtime(true); $result = $this->db->execute($handle, $args); $total = round(microtime(true) - $start, 4); $this->debug("SQL command executed in '{$total}' seconds.", 'sql_time'); return $result; }
/** * This function grabs the actual results for display * * @param array $ids * @return query result **/ public function getResultsForSphinx($ids) { if (ipsRegistry::$request['content_title_only'] == 1) { $this->DB->build(array('select' => "t.*", 'from' => array('topics' => 't'), 'where' => 't.tid IN( ' . implode(',', $ids) . ')', 'order' => 't.last_post DESC', 'add_join' => array(array('select' => 'p.*', 'from' => array('posts' => 'p'), 'where' => 'p.pid=t.topic_firstpost', 'type' => 'left'), array('from' => array('forums' => 'f'), 'where' => 'f.id=t.forum_id', 'type' => 'left'), array('select' => 'm.member_id, m.members_display_name, m.members_seo_name', 'from' => array('members' => 'm'), 'where' => 'm.member_id=p.author_id', 'type' => 'left')))); } else { $this->DB->build(array('select' => "p.*", 'from' => array('posts' => 'p'), 'where' => 'p.pid IN( ' . implode(',', $ids) . ')', 'order' => 'p.post_date DESC', 'add_join' => array(array('select' => 't.*', 'from' => array('topics' => 't'), 'where' => 't.tid=p.topic_id', 'type' => 'left'), array('from' => array('forums' => 'f'), 'where' => 'f.id=t.forum_id', 'type' => 'left'), array('select' => 'm.member_id, m.members_display_name, m.members_seo_name', 'from' => array('members' => 'm'), 'where' => 'm.member_id=p.author_id', 'type' => 'left')))); } return $this->DB->execute(); }
/** * Resets the order of all rows * * @return KDatabaseTableAbstract */ public function reorder() { if (!in_array('ordering', $this->getColumns())) { throw new KDatabaseTableException("The table " . $this->getTableName() . " doesn't have a 'ordering' column."); } $this->_db->execute("SET @order = 0"); $this->_db->execute('UPDATE #__' . $this->getTableName() . ' ' . 'SET ordering = (@order := @order + 1) ' . 'ORDER BY ordering ASC'); return $this; }
/** * Pass the execution request to the parent object, return value is * passed back through to the caller. * * @param string $uri The URI of the request * @param array $params The parameters of the request * @param string $method The HTTP method to use * @return object Guzzle Response object */ public function execute($uri, $params = [], $method = 'get') { if ($uri === '') { $uri = $this->name; } else { $uri = sprintf('%s/%s', $this->name, $uri); } return $this->parent->execute($uri, $params, $method); }
/** * Suppression d'un module * * @param string $id * @return boolean */ public function deleteModule($id) { $query = 'DELETE FROM ' . $this->t_modules . ' ' . 'WHERE module_id=\'' . $this->db->escapeStr($id) . '\' '; if ($this->db->execute($query) === false) { return false; } $this->db->optimize($this->t_modules); return true; }
/** * Store extra information * * @param int $reservationId * @param int $roomId * @param string $roomLabel * @param int $extraId * @param string $extraName * @param int $extraQuantity The extra quantity or NULL if extra does not have quantity * @param int $price * * @return void */ public function storeExtra($reservationId, $roomId, $roomLabel, $extraId, $extraName, $extraQuantity = NULL, $price = 0) { $query = $this->_dbo->getQuery(true); $query->insert($this->_dbo->quoteName('#__sr_reservation_room_extra_xref')); $query->columns(array($this->_dbo->quoteName('reservation_id'), $this->_dbo->quoteName('room_id'), $this->_dbo->quoteName('room_label'), $this->_dbo->quoteName('extra_id'), $this->_dbo->quoteName('extra_name'), $this->_dbo->quoteName('extra_quantity'), $this->_dbo->quoteName('extra_price'))); $query->values($this->_dbo->quote($reservationId) . ',' . $this->_dbo->quote($roomId) . ',' . $this->_dbo->quote($roomLabel) . ',' . $this->_dbo->quote($extraId) . ',' . $this->_dbo->quote($extraName) . ',' . ($extraQuantity === NULL ? NULL : $this->_dbo->quote($extraQuantity)) . ',' . $this->_dbo->quote($price)); $this->_dbo->setQuery($query); $this->_dbo->execute(); }
/** * @param int $roomtypeId * @param int $extraId * @return bool|mixed */ public function storeExtra($roomtypeId = 0, $extraId = 0) { if ($roomtypeId <= 0 && $extraId <= 0) { return false; } $query = $this->_dbo->getQuery(true); $query->insert($this->_dbo->quoteName('#__sr_room_type_extra_xref'))->columns(array($this->_dbo->quoteName('room_type_id'), $this->_dbo->quoteName('extra_id')))->values((int) $roomtypeId . ',' . (int) $extraId); $this->_dbo->setQuery($query); return $this->_dbo->execute(); }
/** * Création de l'ID HTML d'un champ donné * * @param integer $post_id * @return boolean */ protected function setFieldHtmlId($iFieldId) { $rs = $this->getField($iFieldId); $html_id = $this->buildFieldHtmlId($rs->title, $rs->html_id, $iFieldId); $query = 'UPDATE ' . $this->t_fields . ' SET ' . 'html_id=\'' . $this->db->escapeStr($html_id) . '\' ' . 'WHERE id=' . (int) $iFieldId; if (!$this->db->execute($query)) { return false; } return true; }
/** * Met à jour la position d'un élément donné. * * @param integer $iItemId * @param integer $iPosition * @return boolean */ public function updItemOrder($iItemId, $iPosition) { if (!$this->itemExists($iItemId)) { throw new Exception(sprintf(__('c_a_config_navigation_item_%s_not_exists'), $iItemId)); } $query = 'UPDATE ' . $this->t_items . ' SET ' . 'ord=' . (int) $iPosition . ' ' . 'WHERE id=' . (int) $iItemId; if (!$this->db->execute($query)) { throw new Exception('Unable to update item in database.'); } return true; }
/** * Executes a prepared statement. * * If the prepared statement included parameter markers, you must either: * call PDOStatement->bindParam() to bind PHP variables to the parameter markers: * bound variables pass their value as input and receive the output value, * if any, of their associated parameter markers or pass an array of input-only * parameter values. * * @param array $params An array of values with as many elements as there are * bound parameters in the SQL statement being executed. * * @return boolean Returns TRUE on success or FALSE on failure. */ public function execute($params = null) { try { return $this->statement->execute($params); } catch (PDOException $e) { //It's empty. } catch (Doctrine_Adapter_Exception $e) { $this->statement->getConnection()->rethrowException($e, $this); return false; } }