当前位置: 首页>>代码示例>>PHP>>正文


PHP Database::prepare方法代码示例

本文整理汇总了PHP中Database::prepare方法的典型用法代码示例。如果您正苦于以下问题:PHP Database::prepare方法的具体用法?PHP Database::prepare怎么用?PHP Database::prepare使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Database的用法示例。


在下文中一共展示了Database::prepare方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: insert_comment

 public function insert_comment($sid, $msg, $parent, $author_name, $author_email)
 {
     // Connect to database
     try {
         $handler = new Database();
         // Insert comment to database
         if ($parent !== 'NULL') {
             $handler->beginTransaction();
             // If comment has a parent begin transaction
         }
         $res = $handler->prepare('INSERT INTO `comment`(`sid`, `author_name`, `author_email`, `message`, `parent`) VALUES (:sid, :author_name, :author_email, :message, :parent)');
         $res->execute(array(':sid' => $sid, ':author_name' => $author_name, ':author_email' => $author_email, ':message' => $msg, ':parent' => $parent));
         if ($res->rowCount() !== 1) {
             return false;
         }
         // Get cid of last comment
         $cid = $handler->lastInsertId();
         if ($parent !== 'NULL') {
             $res = $handler->prepare('UPDATE `comment` SET `children` = 1 WHERE `cid` = :parent');
             $res->execute(array(':parent' => $parent));
             $handler->commit();
             // Commit only if both queries succeed
         }
     } catch (PDOException $e) {
         if ($parent !== 'NULL') {
             $handler->rollback();
         }
         return false;
     }
     return $cid;
 }
开发者ID:TomOndiba,项目名称:php-infinite-multi-level-comments,代码行数:31,代码来源:CommentHandler.php

示例2: evolve

 public function evolve($buildingId)
 {
     $query = "\n            SELECT\n                ubl.building_id as 'Id',\n                ubl.level_id AS 'Level',\n                bl.gold AS 'Gold',\n                bl.food AS 'Food'\n            FROM users_buildings_levels ubl\n            JOIN buildings b\n                ON b.id = ubl.building_id\n            JOIN building_levels bl\n                ON bl.building_id = ubl.building_id AND bl.level = ubl.level_id + 1\n            WHERE ubl.user_id = ? AND ubl.building_id = ?\n        ";
     $result = $this->database->prepare($query);
     $result->execute([$_SESSION['id'], $buildingId]);
     $building = $result->fetch(\PDO::FETCH_ASSOC);
     if ($this->user->getGold() < $building['Gold'] || $this->user->getFood() < $building['Food']) {
         throw new \Exception('Insufficient resource to evolve building');
     }
     if ($building['Level'] == 3) {
         throw new \Exception('Building has reached maximum level and cannot be evolved');
     }
     $resourceUpdate = "\n            UPDATE users\n            SET gold = ?, food = ?\n            WHERE id = ?\n        ";
     $result = $this->database->prepare($resourceUpdate);
     $result->execute([$this->user->getGold() - $building['Gold'], $this->user->getFood() - $building['Food'], $_SESSION['id']]);
     if ($result) {
         $buildingUpdate = "\n                UPDATE users_buildings_levels\n                SET level_id = ?\n                WHERE user_id = ? AND building_id = ?\n            ";
         $result = $this->database->prepare($buildingUpdate);
         $result->execute([$building['Level'] + 1, $_SESSION['id'], $buildingId]);
         if ($result) {
             return true;
         }
         throw new \Exception('Error occurred while upgrading building');
     }
     throw new \Exception('Error occurred while upgrading building');
 }
开发者ID:OmniPot,项目名称:SoftUni-Level-3-Backend,代码行数:26,代码来源:BuildingsRepository.php

示例3: getBuildings

 public function getBuildings()
 {
     $result = $this->db->prepare("\n            SELECT b.id, b.name, bl.level, bl.gold, bl.food\n            FROM players_buildings ub\n            LEFT JOIN buildings b ON b.id = ub.building_id\n            LEFT JOIN levels bl ON bl.building_id = b.id AND bl.level = ub.level_id + 1\n            WHERE user_id = ?");
     $user_id = $this->getUser()->getId();
     $result->execute([$user_id]);
     return $result->fetchAll();
 }
开发者ID:Aleksandyr,项目名称:Software-University,代码行数:7,代码来源:BuildingsRepository.php

示例4: saveLayerRelations

 /**
  * Save layer relations.
  *
  * @param mixed          $layerId       The layer id values.
  * @param \DataContainer $dataContainer The dataContainer driver.
  *
  * @return null
  */
 public function saveLayerRelations($layerId, $dataContainer)
 {
     $new = deserialize($layerId, true);
     $values = array();
     $result = $this->database->prepare('SELECT * FROM tl_leaflet_map_layer WHERE mid=? order BY sorting')->execute($dataContainer->id);
     while ($result->next()) {
         $values[$result->lid] = $result->row();
     }
     $sorting = 0;
     foreach ($new as $layerId) {
         if (!isset($values[$layerId])) {
             $this->database->prepare('INSERT INTO tl_leaflet_map_layer %s')->set(array('tstamp' => time(), 'lid' => $layerId, 'mid' => $dataContainer->id, 'sorting' => $sorting))->execute();
             $sorting += 128;
         } else {
             if ($values[$layerId]['sorting'] <= $sorting - 128 || $values[$layerId]['sorting'] >= $sorting + 128) {
                 $this->database->prepare('UPDATE tl_leaflet_map_layer %s WHERE id=?')->set(array('tstamp' => time(), 'sorting' => $sorting))->execute($values[$layerId]['id']);
             }
             $sorting += 128;
             unset($values[$layerId]);
         }
     }
     $ids = array_map(function ($item) {
         return $item['id'];
     }, $values);
     if ($ids) {
         $this->database->query('DELETE FROM tl_leaflet_map_layer WHERE id IN(' . implode(',', $ids) . ')');
     }
     return null;
 }
开发者ID:pfitz,项目名称:contao-leaflet-maps,代码行数:37,代码来源:Map.php

示例5: loadPermissions

 /**
  * Load permissions for the given row id.
  *
  * @param int $rowId The road id.
  *
  * @return void
  */
 private function loadPermissions($rowId)
 {
     $permissions = array();
     $result = $this->database->prepare('SELECT * FROM tl_workflow_permission WHERE source=? AND source_id=?')->execute($this->source, $rowId);
     while ($result->next()) {
         $permissions[$result->permission] = $result->id;
     }
     $this->permissions = $permissions;
 }
开发者ID:netzmacht,项目名称:contao-workflow,代码行数:16,代码来源:SavePermissionsCallback.php

示例6: delete

 /**
  * Set row's active field to 0. We don't delete rows from database for sake of keeping it consistent
  * @param $id
  * @param $table
  * @return array
  */
 public function delete($id, $table)
 {
     $query = "UPDATE " . $table;
     $query .= ' SET active = 0 WHERE id = ? AND store_id = ?';
     $preparedObj = $this->_db->prepare($query);
     $preparedObj->bind_param('ii', $id, $this->store_id);
     $preparedObj->execute();
     $results = $preparedObj->get_result();
     return $this->result_array($results);
 }
开发者ID:ezelohar,项目名称:form-validation,代码行数:16,代码来源:ModelClass.php

示例7: startQuery

 private function startQuery($search_string)
 {
     $database = new Database();
     $database->Create(new EventTable());
     /*
                 
                $sqlFullText= "CREATE FULLTEXT INDEX If Not Exists search ON ".EventTable::TableName.
                        "(".EventTable::Title.",".
                         EventTable::Description.",".
                         EventTable::SeachableKeywords.",".
                         EventTable::Venue.")";
                 
                  * ".EventTable::Title, "(".EventTable::Title.","
                           .EventTable::Description.",".EventTable::SeachableKeywords.",".EventTable::Venue."
                  * 
                 $database->runCommand($sqlFullText);
                  * */
     $query_string = $database->quote($search_string);
     $squery = "select *from " . EventTable::TableName . " WHERE ( MATCH (" . EventTable::Title . "," . EventTable::Description . "," . EventTable::SeachableKeywords . "," . EventTable::Venue . ") AGAINST ({$query_string} IN BOOLEAN MODE)) AND " . EventTable::Status . " > :zero";
     $stmt = $database->prepare($squery);
     $stmt->bindValue(":zero", 0);
     $status = $stmt->execute();
     if ($status) {
         $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
         for ($i = 0; $i < count($rows); $i++) {
             $rows[$i][EventTable::Image] = IMAGE_EVENT_PATHS . $rows[$i][EventTable::Image];
         }
         return $rows;
     } else {
         print_r($stmt->errorInfo());
         return null;
     }
 }
开发者ID:jimobama,项目名称:fffddffd,代码行数:33,代码来源:TrySearchEventWithQueryStrings.php

示例8: validateToken

 static function validateToken($token)
 {
     $db = new Database();
     $query = $db->prepare("SElECT * FROM password_resets where token = :token");
     $query->bindParam(':token', $token);
     $query->execute();
     $data = $query->fetch(PDO::FETCH_ASSOC);
     if (!self::checkTokenDate(strtotime($data['created_at']))) {
         // if self::checkExpirationDate returns 'false'
         $query = $db->prepare("DELETE FROM password_resets where token = :token");
         $query->bindParam(':token', $token);
         $query->execute();
         $_SESSION['error_message'] = self::$ER_MSG;
         View::render('index.php');
     }
 }
开发者ID:Adrian268,项目名称:comp296,代码行数:16,代码来源:Token.php

示例9: initAccount

 public function initAccount($certrow)
 {
     // Let's see if we have the private accountkey
     $this->accountKey = $certrow['leprivatekey'];
     if (!$this->accountKey || $this->accountKey == 'unset' || Settings::Get('system.letsencryptca') != 'production') {
         // generate and save new private key for account
         // ---------------------------------------------
         $this->log('Starting new account registration');
         $keys = $this->generateKey();
         // Only store the accountkey in production, in staging always generate a new key
         if (Settings::Get('system.letsencryptca') == 'production') {
             $upd_stmt = Database::prepare("UPDATE `" . TABLE_PANEL_CUSTOMERS . "` SET `lepublickey` = :public, `leprivatekey` = :private " . "WHERE `customerid` = :customerid;");
             Database::pexecute($upd_stmt, array('public' => $keys['public'], 'private' => $keys['private'], 'customerid' => $certrow['customerid']));
         }
         $this->accountKey = $keys['private'];
         $response = $this->postNewReg();
         if ($this->client->getLastCode() != 201) {
             throw new \RuntimeException("Account not initialized, probably due to rate limiting. Whole response: " . $response);
         }
         $this->postNewReg();
         $this->log('New account certificate registered');
     } else {
         $this->log('Account already registered. Continuing.');
     }
 }
开发者ID:asemen,项目名称:Froxlor,代码行数:25,代码来源:class.lescript.php

示例10: updateEvent

 private function updateEvent($user_id, $user_password, $event_id, $searchablekeywords)
 {
     $response = array();
     $response["success"] = 0;
     $jsonView = new JsonViewer();
     $tryLogin = new TryUserLogin($user_id, $user_password);
     if ($tryLogin->isExists()) {
         //update the events
         $database = new Database();
         $sql = "UPDATE " . EventTable::TableName . " set " . EventTable::SeachableKeywords . "=:search_keys WHERE " . EventTable::Id . "=:id";
         $smt = $database->prepare($sql);
         $smt->bindValue(":id", $event_id);
         $smt->bindValue(":search_keys", $searchablekeywords);
         $status = $smt->execute();
         if ($status) {
             $response["success"] = 1;
             $response["message"] = "update searchable keys";
         } else {
             $response["error_message"] = "Invalid event details provided";
         }
     } else {
         $response["error_message"] = "Invalid login details";
     }
     $jsonView->setContent($response);
     return $jsonView;
 }
开发者ID:jimobama,项目名称:fffddffd,代码行数:26,代码来源:TryUpdateSearchableKeywordController.php

示例11: loadSettings

/**
 * @FIXME remove when fully migrated to new Settings class
 *
 * @param array $settings_data
 *
 * @return array
 */
function loadSettings(&$settings_data)
{
    $settings = array();
    if (is_array($settings_data) && isset($settings_data['groups']) && is_array($settings_data['groups'])) {
        // prepare for use in for-loop
        $row_stmt = Database::prepare("\n\t\t\tSELECT `settinggroup`, `varname`, `value`\n\t\t\tFROM `" . TABLE_PANEL_SETTINGS . "`\n\t\t\tWHERE `settinggroup` = :group AND `varname` = :varname\n\t\t");
        foreach ($settings_data['groups'] as $settings_part => $settings_part_details) {
            if (is_array($settings_part_details) && isset($settings_part_details['fields']) && is_array($settings_part_details['fields'])) {
                foreach ($settings_part_details['fields'] as $field_name => $field_details) {
                    if (isset($field_details['settinggroup']) && isset($field_details['varname']) && isset($field_details['default'])) {
                        // execute prepared statement
                        $row = Database::pexecute_first($row_stmt, array('group' => $field_details['settinggroup'], 'varname' => $field_details['varname']));
                        if (!empty($row)) {
                            $varvalue = $row['value'];
                        } else {
                            $varvalue = $field_details['default'];
                        }
                        $settings[$field_details['settinggroup']][$field_details['varname']] = $varvalue;
                    } else {
                        $varvalue = false;
                    }
                    $settings_data['groups'][$settings_part]['fields'][$field_name]['value'] = $varvalue;
                }
            }
        }
    }
    return $settings;
}
开发者ID:cobrafast,项目名称:Froxlor,代码行数:35,代码来源:function.loadSettings.php

示例12: parent

 public static function parent($parent)
 {
     if ($parent === null) {
         // If parent is null
         return true;
     } else {
         if ($parent < 1) {
             // If parent not positive
             return false;
         } else {
             // Check if parent id exists
             // Connect to database
             try {
                 $handler = new Database();
                 // Query database to see if parent id exists
                 $res = $handler->prepare('SELECT `cid` FROM `comment` WHERE `cid` = :parent');
                 $res->execute(array(':parent' => $parent));
             } catch (PDOException $e) {
                 return false;
             } catch (Exception $e) {
                 return false;
             }
             if ($res->rowCount() === 1) {
                 return true;
             }
             return false;
         }
     }
 }
开发者ID:TomOndiba,项目名称:php-infinite-multi-level-comments,代码行数:29,代码来源:Validation.php

示例13: editUser

 public function editUser(User $newData)
 {
     $updateQuery = "UPDATE users SET password = ?, username = ? WHERE id = ?";
     $result = $this->database->prepare($updateQuery);
     $result->execute([$newData->getPassword(), $newData->getUsername(), $newData->getId()]);
     return $result->rowCount() > 0;
 }
开发者ID:OmniPot,项目名称:SoftUni-Level-3-Backend,代码行数:7,代码来源:App.php

示例14: log

	/**
	 * Add a log entry
	 * @param string
	 * @param string
	 * @param string
	 */
	protected function log($strText, $strFunction, $strAction)
	{
		$this->import('Database');

		$strUa = 'N/A';
		$strIp = '127.0.0.1';

		if ($this->Environment->httpUserAgent)
		{
			$strUa = $this->Environment->httpUserAgent;
		}
		if ($this->Environment->remoteAddr)
		{
			$strIp = $this->anonymizeIp($this->Environment->remoteAddr);
		}

		$this->Database->prepare("INSERT INTO tl_log (tstamp, source, action, username, text, func, ip, browser) VALUES(?, ?, ?, ?, ?, ?, ?, ?)")
					   ->execute(time(), (TL_MODE == 'FE' ? 'FE' : 'BE'), $strAction, ($GLOBALS['TL_USERNAME'] ? $GLOBALS['TL_USERNAME'] : ''), specialchars($strText), $strFunction, $strIp, $strUa);

		// HOOK: allow to add custom loggers
		if (isset($GLOBALS['TL_HOOKS']['addLogEntry']) && is_array($GLOBALS['TL_HOOKS']['addLogEntry']))
		{
			foreach ($GLOBALS['TL_HOOKS']['addLogEntry'] as $callback)
			{
				$this->import($callback[0]);
				$this->$callback[0]->$callback[1]($strText, $strFunction, $strAction);
			}
		}
	}
开发者ID:narrenfrei,项目名称:core,代码行数:35,代码来源:System.php

示例15: getGraphHeader

function getGraphHeader($database, $photoID)
{
    if (!isset($database, $photoID)) {
        return false;
    }
    $query = Database::prepare($database, "SELECT title, description, url, medium FROM ? WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $photoID));
    $result = $database->query($query);
    $row = $result->fetch_object();
    if ($row->medium === '1') {
        $dir = 'medium';
    } else {
        $dir = 'big';
    }
    $parseUrl = parse_url('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    $picture = $parseUrl['scheme'] . '://' . $parseUrl['host'] . $parseUrl['path'] . '/../uploads/' . $dir . '/' . $row->url;
    $return = '<!-- General Meta Data -->';
    $return .= '<meta name="title" content="' . $row->title . '" />';
    $return .= '<meta name="description" content="' . $row->description . ' - via Lychee" />';
    $return .= '<link rel="image_src" type="image/jpeg" href="' . $picture . '" />';
    $return .= '<!-- Twitter Meta Data -->';
    $return .= '<meta name="twitter:card" content="photo">';
    $return .= '<meta name="twitter:title" content="' . $row->title . '">';
    $return .= '<meta name="twitter:image:src" content="' . $picture . '">';
    $return .= '<!-- Facebook Meta Data -->';
    $return .= '<meta property="og:title" content="' . $row->title . '">';
    $return .= '<meta property="og:image" content="' . $picture . '">';
    return $return;
}
开发者ID:jonsychen,项目名称:docker-picture-gallery,代码行数:28,代码来源:misc.php


注:本文中的Database::prepare方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。