/** * Returns a PDOStatement * * This method will return the same object for equal queries. * * @param string $sql * @return \PDOStatement * @throws \PDOException */ public function prepare($sql) { if (!array_key_exists($sql, $this->statements)) { $this->statements[$sql] = $this->pdo->prepare($sql); } return $this->statements[$sql]; }
/** * Prepares a sql statement to be executed * * @param string|\Cake\Database\Query $query The query to turn into a prepared statement. * @return \Cake\Database\StatementInterface */ public function prepare($query) { $this->connect(); $isObject = $query instanceof Query; $statement = $this->_connection->prepare($isObject ? $query->sql() : $query); return new PDOStatement($statement, $this); }
public static function moveFile($file) { $dir = 'upload/' . time() . '_'; $filename = $dir . $file['name']; $result = ''; if (move_uploaded_file($file['tmp_name'], $filename)) { try { $bdd = new \PDO('mysql:host=localhost;dbname=ecvd_php', 'root', ''); } catch (Exception $e) { die('Erreur : ' . $e->getMessage()); } try { $insert_file = $bdd->prepare("INSERT INTO `ecvd_php`.`files` (`id`, `filename`, `path`, `extension`) VALUES ('', ?, ?, ?)"); $insert_file->execute(array($file['name'], $dir, $file['type'])); $result = 'Good !'; } catch (Exception $e) { $result = 'Erreur !'; } try { $update = $bdd->prepare("UPDATE `users` SET `image_id`= ? WHERE `username` = ?"); $update->execute(array($bdd->lastInsertId(), $_SESSION['username'])); $result = 'Good !'; } catch (Exception $e) { $result = 'Erreur !'; // die("Some error occured while the updating process : ".$e); } } else { $result = 'Erreur !'; } return $result; }
protected function existRow($query) { $statement = self::$dbh->prepare($query); $statement->execute(); $result = $statement->fetchAll(); return isset($result[0]['cnt']) && 1 === (int) $result[0]['cnt']; }
public function it_should_be_able_to_delete_an_object(\PDOStatement $pdoStatement) { $uuid = Uuid::uuid4(); $this->pdo->prepare(new TypeToken('string'))->willReturn($pdoStatement); $pdoStatement->execute(['uuid' => $uuid->getBytes(), 'type' => 'test'])->shouldBeCalled(); $this->delete('test', $uuid); }
public function testHydrateAll_行が存在しないとき空配列を返す() { $hydrator = new Mappa\Hydrator(); $stmt = $this->conn->prepare("SELECT * FROM books JOIN categories ON categories.id = books.category_id WHERE books.id = ?"); $stmt->execute([100]); $this->assertSame([], $hydrator->hydrateAll($stmt, [Book::class, Category::class])); }
/** * Adds a new version to an application. * * @param array $info Hash with the version information. Possible keys: * - application: (string) The name of the application. * - version: (string) The version string. * - state: (string) The version state. One of * "stable", "dev", "three". By default * automatically detected from "version. * - date: (DateTime) The release date. Defaults to * today. * - pear: (boolean) A PEAR release? Defaults to true. * - dir: (string) Optional website directory, if not * "application". * * @throws Horde_Exception */ public function addNewVersion(array $info = array()) { if (!isset($info['application']) || !isset($info['version'])) { throw new LogicException('Missing parameter'); } $info = array_merge(array('state' => $this->_stateFromVersion($info['version']), 'date' => new DateTime(), 'pear' => true, 'dir' => null), $info); if (!in_array($info['state'], array('stable', 'dev', 'three'))) { throw new LogicException('Invalid state ' . $info['state']); } $info['date'] = $info['date']->format('Y-m-d'); $bind = array(); foreach ($info as $key => $value) { $bind[':' . $key] = $value; } try { $stmt = $this->_db->prepare('SELECT 1 FROM versions WHERE application = :application AND state = :state'); $stmt->execute(array(':application' => $info['application'], ':state' => $info['state'])); $stmt = $stmt->fetchColumn() ? $this->_db->prepare('UPDATE versions SET version = :version, date = :date, pear = :pear, dir = :dir WHERE application = :application AND state = :state') : $this->_db->prepare('INSERT INTO versions (application, state, version, date, pear, dir) VALUES (:application, :state, :version, :date, :pear, :dir)'); if (!$stmt->execute($bind)) { $error = $stmt->errorInfo(); throw new Horde_Exception($error[2], $error[1]); } } catch (PDOException $e) { throw new Horde_Exception($e); } }
public function findBySlug($slug) { $sql = "SELECT * FROM sections WHERE slug = :slug"; $stmt = $this->db->prepare($sql); $stmt->execute(['slug' => $slug]); return $stmt->fetch(\PDO::FETCH_ASSOC); }
/** * Queries the Auth table */ public function query($params = array(), $operator = "OR") { $page = intval(@$params['page']); $size = intval(@$params['size']); $sort = @$params['sort']; unset($params['page']); unset($params['size']); unset($params['sort']); if (!$size) { $size = 20; } $cond = array(); $bindings = array(); foreach ($params as $key => $value) { $cond[] = sprintf("`%s` %s :where_%s", str_replace('`', '``', $key), is_null($value) ? 'is' : (strpos($value, '%') !== FALSE ? 'LIKE' : '='), $key); $bindings[":where_{$key}"] = $value; } $query = sprintf(self::SELECT_SEARCH, $this->params['table'], empty($cond) ? '1=1' : implode(" {$operator} ", $cond)); $query .= sprintf(" LIMIT %d, %d", $page * $size, $size); $stmt = $this->pdo->prepare($query); $stmt->execute($bindings); if (!$stmt) { $error = $this->pdo->errorInfo(); throw new \Exception($error[2]); } $data = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt = $this->pdo->query("SELECT FOUND_ROWS() as count"); $count = $stmt->fetch(PDO::FETCH_ASSOC); if (!$count) { throw new \Exception("Error fetching count"); } $count = intval($count['count']); return array('_embedded' => array($this->params['table'] => $data), 'page' => array('size' => $size, 'number' => $page, 'totalElements' => $count, 'totalPages' => ceil($count / $size))); }
/** * Every method which needs to execute a SQL query uses this method. * * 1. If not connected, connect to the database. * 2. Prepare Query. * 3. Parameterize Query. * 4. Execute Query. * 5. On exception : Write Exception into the log + SQL query. * 6. Reset the Parameters. */ private function Init($query, $parameters = "") { # Connect to database if (!$this->bConnected) { $this->Connect(); } try { # Prepare query $this->sQuery = $this->pdo->prepare($query); # Add parameters to the parameter array $this->bindMore($parameters); # Bind parameters if (!empty($this->parameters)) { foreach ($this->parameters as $param) { $parameters = explode("", $param); $this->sQuery->bindParam($parameters[0], $parameters[1]); } } # Execute SQL $this->success = $this->sQuery->execute(); } catch (\PDOException $e) { # Write into log and display Exception $this->ExceptionLog($e->getMessage(), $query); throw new \Exception($e->getMessage()); } # Reset the parameters $this->parameters = array(); }
/** * Prepares a statement for execution and returns a statement object * * @param string $statement * A valid SQL statement for the target database server * @param array $driver_options * Array of one or more key=>value pairs to set attribute values for the PDOStatement obj * returned * @return PDOStatement */ public function prepare($statement, $driver_options = false) { if (!$driver_options) { $driver_options = array(); } return $this->PDOInstance->prepare($statement, $driver_options); }
public function __construct($dsn) { $db = new \PDO($dsn); $db->query(self::ERZEUGE_TABELLE); $this->getDay = $db->prepare(self::LESE_TAG); $this->getAlleBis = $db->prepare(self::LESE_ALLE_BIS); }
function removeArticle($id) { $query = "DELETE FROM articles WHERE id = :id"; $stmt = $this->dbh->prepare($query); $stmt->bindParam(":id", $id, PDO::PARAM_INT); return $stmt->execute(); }
/** * Migrate CMI Worpress posts to Backdrop CMS blog content type. * 0: "ID", * 1: "post_author", * 2: "post_date", * 3: "post_date_gmt", * 4: "post_content", * 5: "post_title", * 6: "post_excerpt", * 7: "post_status", * 8: "comment_status", * 9: "ping_status", * 10: "post_password" => NOT USED, * 11: "post_name", * 12: "to_ping", * 13: "pinged", * 14: "post_modified", * 15: "post_modified_gmt", * 16: "post_content_filtered", * 17: "post_parent", * 18: "guid", * 19: "menu_order", * 20: "post_type", * 21: "post_mime_type", * 22: "comment_count" */ function run_migrate_posts() { $user = '******'; $pass = '******'; $wpdb = new PDO('mysql:host=localhost;dbname=cmi_wp', $user, $pass); $bddb = new PDO('mysql:host=localhost;dbname=backdrop_cmi', $user, $pass); $sql = $wpdb->prepare("select * from wp_posts where post_type = 'post' and post_content != ''"); $sql->execute(); $data = $sql->fetchAll(); $blog_sql = $bddb->prepare("insert into node (\n nid,\n vid,\n type,\n langcode,\n title,\n uid,\n status,\n created,\n changed,\n comment,\n promote,\n sticky,\n tnid,\n translate\n ) values (\n :nid,\n :vid,\n :type,\n :langcode,\n :title,\n :uid,\n :status,\n :created,\n :changed,\n :comment,\n :promote,\n :sticky,\n :tnid,\n :translate\n )"); $body_query = $bddb->prepare("insert into field_data_body (\n entity_type,\n bundle,\n deleted,\n entity_id,\n revision_id,\n language,\n delta,\n body_value,\n body_summary,\n body_format\n ) values (\n 'node',\n 'blog',\n 0,\n :entity_id,\n :revision_id,\n 'und',\n 0,\n :body_value,\n NULL,\n 'full_html'\n )"); //$i = 79; foreach ($data as $d) { $post_author = $d['post_author'] + 1; $post_date = strtotime($d['post_date']); $post_changed = strtotime($d['post_modified']); $blog_binds = array(':nid' => $d['ID'], ':vid' => $d['ID'], ':type' => 'blog', ':langcode' => 'und', ':title' => $d['post_title'], ':uid' => $post_author, ':status' => 1, ':created' => $post_date, ':changed' => $post_changed, ':comment' => 0, ':promote' => 0, ':sticky' => 0, ':tnid' => 0, ':translate' => 0); $blog_sql->execute($blog_binds) or die(print_r($blog_sql->errorInfo(), true)); print $d['post_author'] + 1 . " " . $post_date . "\n"; $body_binds = array(':entity_id' => $d['ID'], ':revision_id' => $d['ID'], ':body_value' => $d['post_content']); $body_query->execute($body_binds) or die(print_r($body_query->errorInfo(), true)); //$i++; } print "CMI wp-posts to Backdrop CMS blog content type complete.\n"; }
public function flush() { foreach ($this->clientes as $cliente) { $stmt = $this->pdo->prepare("INSERT INTO clientes_poo(\n nome,nome_empresa,tipo_cliente, endereco, nvlImportancia, telefone,\n endereco_cobranca,cpf,cnpj,filiacao)\n VALUES(:nome, :nomeEmpresa,:tipoCliente,:endereco, :nvlImportancia, :telefone,:enderecoCobranca, :cpf, :cnpj,:filiacao)"); $stmt->bindValue(":tipoCliente", $cliente->getTipoCliente()); $stmt->bindValue(":endereco", $cliente->getEndereco()); $stmt->bindValue(":nvlImportancia", $cliente->getNvlImportancia()); $stmt->bindValue(":telefone", $cliente->getTelefone()); if ($cliente->getEnderecoCobranca()) { $stmt->bindValue(":enderecoCobranca", $cliente->getEnderecoCobranca()); } else { $stmt->bindValue(":enderecoCobranca", null); } if ($cliente instanceof ClientePessoaFisica) { $stmt->bindValue(":cpf", $cliente->getCpf()); $stmt->bindValue(":cnpj", null); $stmt->bindValue(":nome", $cliente->getNome()); $stmt->bindValue(":nomeEmpresa", null); $stmt->bindValue(":filiacao", $cliente->getFiliacao()); } else { $stmt->bindValue(":cnpj", $cliente->getCnpj()); $stmt->bindValue(":cpf", null); $stmt->bindValue(":nomeEmpresa", $cliente->getNomeEmpresa()); $stmt->bindValue(":nome", null); $stmt->bindValue(":filiacao", null); } $stmt->execute(); } }
public function push($url, $deep) { $query = $this->db->prepare('INSERT OR IGNORE INTO queue (url, deep) VALUES (:url, :deep)'); $query->bindValue(':url', $url); $query->bindValue(':deep', $deep); $query->execute(); }
/** \brief Updates database ticket with stored image url * \param picture_url Part of URL to the image * \param upload_dir Directory in which the images are stored * \param interaction_id Ticket identifier for updated image * \returns Successful database update or unsuccessful */ function updatePicture($picture_url, $upload_dir, $interaction_id) { try { require "/var/database_config.php"; $pdo = new PDO('mysql:host=' . $db_config['host'] . ';dbname=' . $db_config['dbname'], $db_config['username'], $db_config['password']); $sql_str = "SELECT image from tickets WHERE interaction_id = ?"; $statement = $pdo->prepare($sql_str); $statement->execute(array($interaction_id)); $picture = $statement->fetch(PDO::FETCH_ASSOC); if ($picture['image'] !== NULL) { $temp = explode("/", $picture['image']); $file = end($temp); $picture_path = $upload_dir . $file; if (file_exists($picture_path)) { if (unlink($picture_path)) { //return array('status' => 'File deleted'); } } } $sql_str = "UPDATE tickets SET image = ? WHERE interaction_id = ?"; $statement = $pdo->prepare($sql_str); $statement->execute(array($picture_url, $interaction_id)); $logs = array(); $logs[] = "Image added to ticket."; require "../log.php"; writeLog($interaction_id, $logs); return array('status' => 'Successful image update'); } catch (PDOException $e) { return array('error' => 'Error updating the image in the database'); } }
/** * Validates a username and password * * This method should return true or false depending on if login * succeeded. * * @param string $username * @param string $password * @return bool */ function validateUserPass($username, $password) { $stmt = $this->pdo->prepare('SELECT ' . $this->passwordField . ' FROM ' . $this->tableName . ' WHERE ' . $this->usernameField . ' = ?'); $stmt->execute([$username]); $hash = $stmt->fetchColumn(); return password_verify($password, $hash) ?: null; }
function formthrottle_too_many_submissions($ip) { $tooManySubmissions = false; try { if (in_array("sqlite", PDO::getAvailableDrivers(), TRUE)) { $db = new PDO('sqlite:muse-throttle-db.sqlite3'); } else { if (function_exists("sqlite_open")) { $db = new PDO('sqlite2:muse-throttle-db'); } } } catch (PDOException $Exception) { return $tooManySubmissions; } if ($db) { $res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';"); if (!$res or $res->fetchColumn() == 0) { $db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)"); } $db->exec("DELETE FROM Submission_History WHERE Submission_Date < DATETIME('now','-2 hours')"); $stmt = $db->prepare("INSERT INTO Submission_History (IP,Submission_Date) VALUES (:ip, DATETIME('now'))"); $stmt->bindParam(':ip', $ip); $stmt->execute(); $stmt->closeCursor(); $stmt = $db->prepare("SELECT COUNT(1) FROM Submission_History WHERE IP = :ip;"); $stmt->bindParam(':ip', $ip); $stmt->execute(); if ($stmt->fetchColumn() > 25) { $tooManySubmissions = true; } // Close file db connection $db = null; } return $tooManySubmissions; }
public function __construct() { parent::__construct(); $pdo = new PDO('sqlite::memory:'); $artists = [['name' => 'The Smashing Pumpkins', 'albums' => [['name' => 'Siamese Dream', 'year' => 1993, 'songs' => ['Hummer', 'Disarm', 'Soma', 'Mayonaise']], ['name' => 'Pisces Iscariot', 'year' => 1994, 'songs' => ['Plume', 'Whir', 'Landslide']]]], ['name' => 'Placebo', 'albums' => [['name' => 'Without You I\'m Nothing', 'year' => 1998, 'songs' => ['Pure Morning', 'Brick Shithouse', 'You Don\'t Care About Us', 'Allergic (to Thoughts of Mother Earth)', 'Every You Every Me']], ['name' => 'Black Market Music', 'year' => 2000, 'songs' => ['Taste in Men', 'Special K', 'Spice & Malice', 'Black-Eyed', 'Peeping Tom']], ['name' => 'Sleeping With Ghosts', 'year' => 2002, 'songs' => ['English Summer Rain', 'This Picture', 'Special Needs', 'Second Sight', 'Centrefolds']]]], ['name' => 'The Who', 'albums' => [['name' => 'Who\'s Next', 'year' => 1971, 'songs' => ['Baba O\'Riley', 'My Wife', 'Going Mobile', 'Behind Blue Eyes']]]]]; $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $pdo->exec("CREATE TABLE artists (id INTEGER PRIMARY KEY, name TEXT)"); $pdo->exec("CREATE TABLE albums (id INTEGER PRIMARY KEY, name TEXT, year INTEGER, artist_id INTEGER)"); $pdo->exec("CREATE TABLE songs (id INTEGER PRIMARY KEY, name TEXT, track_number INTEGER, album_id INTEGER)"); $insert_artist = $pdo->prepare("INSERT INTO artists (name) VALUES (?)"); $insert_album = $pdo->prepare("INSERT INTO albums (name, year, artist_id) VALUES (?, ?, ?)"); $insert_song = $pdo->prepare("INSERT INTO songs (name, track_number, album_id) VALUES (?, ?, ?)"); $pdo->beginTransaction(); foreach ($artists as $artist) { $insert_artist->execute([$artist['name']]); $artist_id = $pdo->lastInsertId(); foreach ($artist['albums'] as $album) { $insert_album->execute([$album['name'], $album['year'], $artist_id]); $album_id = $pdo->lastInsertId(); foreach ($album['songs'] as $track_number => $song) { $insert_song->execute([$song, $track_number + 1, $album_id]); } } } $this->pdo = $pdo; }
public static function leavePlanet(\PDO $pdo_db, int $ship_id) { $sql = "SELECT * FROM ::prefix::planets WHERE owner=:owner"; $stmt = $pdo_db->prepare($sql); $stmt->bindParam(':owner', $ship_id); $stmt->execute(); $planets_owned = $stmt->fetchAll(\PDO::FETCH_ASSOC); if ($planets_owned !== null) { foreach ($planets_owned as $tmp_planet) { $sql = "SELECT * FROM ::prefix::ships WHERE on_planet='Y' AND planet_id = :planet_id AND ship_id <> :ship_id"; $stmt = $pdo_db->prepare($sql); $stmt->bindParam(':planet_id', $tmp_planet['planet_id']); $stmt->bindParam(':ship_id', $ship_id); $stmt->execute(); $ships_on_planet = $stmt->fetchAll(\PDO::FETCH_ASSOC); if ($ships_on_planet !== null) { foreach ($ships_on_planet as $tmp_ship) { $sql = "UPDATE ::prefix::ships SET on_planet='N', planet_id = '0' WHERE ship_id = :ship_id"; $stmt = $pdo_db->prepare($sql); $stmt->bindParam(':ship_id', $tmp_ship['ship_id']); $stmt->execute(); PlayerLog::WriteLog($pdo_db, $tmp_ship['ship_id'], LOG_PLANET_EJECT, $tmp_ship['sector'] . '|' . $tmp_ship['character_name']); } } } } }
/** * @param PDO $link * @param string $user * @param string $field1 * @param string $field2 * @param string $lang * @param string $group * @param string $id1 * @param string $id2 * @param string $word * @param int $type */ function update($link, $user, $field1, $field2, $lang, $group, $id1, $id2, $word, $type) { $sql = "SELECT associd FROM `associations` WHERE id1 = :id1 AND id2 = :id2 AND word = :word AND user = :user AND assigned_group = :group AND lang = :lang AND type = :type"; $stmt = $link->prepare($sql); $stmt->bindValue(':id1', $id1, PDO::PARAM_STR); $stmt->bindValue(':id2', $id2, PDO::PARAM_STR); $stmt->bindValue(':word', $word, PDO::PARAM_STR); $stmt->bindValue(':type', $type, PDO::PARAM_INT); $stmt->bindValue(':user', $user, PDO::PARAM_STR); $stmt->bindValue(':group', $group, PDO::PARAM_STR); $stmt->bindValue(':lang', $lang, PDO::PARAM_STR); if ($stmt->execute() === false) { error_log(var_export($link->errorInfo(), true)); die("Error performing database operation."); } if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $sql = "INSERT INTO `evaluations` ( associd , evaluator , vote , popvote ) values ( :associd , :user , :vote , :popvote )"; $stmt = $link->prepare($sql); $stmt->bindValue(':associd', $row['associd'], PDO::PARAM_STR); $stmt->bindValue(':user', $_SESSION['user_array']['user'], PDO::PARAM_STR); $stmt->bindValue(':vote', $field1 === 'upvotes' ? 2 : ($field1 === 'neutralvotes' ? 1 : 0), PDO::PARAM_INT); $stmt->bindValue(':popvote', $field2 === 'popupvotes' ? 2 : ($field2 === 'popneutralvotes' ? 1 : 0), PDO::PARAM_INT); if ($stmt->execute() === false) { error_log(var_export($link->errorInfo(), true)); die("Error performing database operation."); } } }
function insert_sql($table, $url, $contents) { try { $dbh = new PDO('sqlite:test.db', '', ''); //PDOクラスのオブジェクト作成 //データベースに格納する $sql = 'insert into ' . $table . '(url,contents) values (?,?)'; //SQL文 $sth = $dbh->prepare($sql); //prepareメソッドでSQL準備 $sth->execute(array($url, $contents)); //準備したSQL文の実行 //データベースを検索し情報を抽出 $q = "'%t%'"; $sql = "select * from {$table} where contents like {$q}"; $sth = $dbh->prepare($sql); $sth->execute(); while ($row = $sth->fetch()) { //echo $row['url'].$row['contents']."<br>"; } } catch (PDOException $e) { print "エラー!: " . $e->getMessage() . "<br/>"; die; } }
/** * @param $sql * @param array $params * @param array $pdoOptions * @return \Framework\DB\SimpleDB */ public function prepare($sql, $params = array(), $pdoOptions = []) { $this->_statement = $this->_db->prepare($sql, $pdoOptions); $this->_params = $params; $this->_sql = $sql; return $this; }
public function getById($id) { if (is_int($id)) { $siglatempo = null; $stm = $this->pdo->prepare('SELECT id, sigla, descricao FROM siglatempo WHERE id = :id;'); $stm->setFetchMode(PDO::FETCH_CLASS, 'PrevisaoTempo\\DataAccess\\Entity\\SiglaTempo'); $stm->bindValue(':id', $id, PDO::PARAM_INT); if ($stm->execute()) { $siglatempo = $stm->fetch(); $stm->closeCursor(); } if (!$siglatempo instanceof SiglaTempo) { throw new \RuntimeException('Falha ao recuparar siglatempo'); } return $siglatempo; } throw new \InvalidArgumentException(print_r($id, true) . ' e um valor invalido'); }
public function prepare($sql, $params = [], $pdoOptions = []) { $this->stmt = $this->db->prepare($sql, $pdoOptions); $this->params = $params; $this->sql = $sql; return $this; }
function authenticate($username, $password) { $db = new PDO('mysql:dbname=dwa;host=localhost;charset=utf8', 'dbuser', '123'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try { $stmt = $db->prepare("SELECT zaporka FROM korisnik WHERE korIme = :username"); $stmt->bindParam(':username', $username); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); $hash = $result['zaporka']; if(!password_verify($password, $hash)) { return false; } $stmt = $db->prepare("SELECT id, korIme, ime FROM korisnik WHERE korIme = :username"); $stmt->bindParam(':username', $username); $stmt->execute(); $user = $stmt->fetch(); $_SESSION['user'] = $user['korIme']; return true; } catch(PDOException $ex) { echo "Nes ne valja: ".$ex->getMessage(); return false; } }
public static function destroy(\PDO $pdo_db, int $sector, $num_fighters) { $sql = "SELECT * FROM ::prefix::sector_defense WHERE sector_id=:sector_id AND defense_type ='F' ORDER BY quantity ASC"; $stmt = $pdo_db->prepare($sql); $stmt->bindParam(':sector_id', $sector); $stmt->execute(); $defense_present = $stmt->fetch(\PDO::FETCH_ASSOC); if ($defense_present !== null && $num_fighters > 0) { foreach ($defense_present as $tmp_defense) { if ($tmp_defense['quantity'] > $num_fighters) { $sql = "UPDATE ::prefix::sector_defense SET quantity = :quantity - ? WHERE defense_id = :defense_id"; $stmt = $pdo_db->prepare($sql); $stmt->bindParam(':quantity', $tmp_defense['quantity']); $stmt->bindParam(':defense_id', $tmp_defense['defense_id']); $stmt->execute(); $num_fighters = 0; } else { $sql = "DELETE FROM ::prefix::sector_defense WHERE defense_id = :defense_id"; $stmt = $pdo_db->prepare($sql); $stmt->bindParam(':defense_id', $tmp_defense['defense_id']); $stmt->execute(); $num_fighters -= $tmp_defense['quantity']; } } } }
function getUserData($username) { try { $userarray = array(); #echo "username: $username<br/>"; $db = new PDO('mysql:dbname=michaeq6_mheartsj', 'michaeq6_mj', 'mj060708'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $db->prepare("SELECT group_id FROM users WHERE name=?"); $stmt->bindParam(1, $username); $completed = $stmt->execute(); $array = $stmt->fetch(PDO::FETCH_BOTH); #echo "group id: " . $array['group_id'] . "<br/>"; $userarray['gid'] = $array['group_id']; $stmt = $db->prepare("SELECT password FROM groups WHERE id=?"); $stmt->bindParam(1, $array['group_id']); $completed = $stmt->execute(); $array = $stmt->fetch(PDO::FETCH_BOTH); #echo "password: "******"<br/>"; $userarray['password'] = $array['password']; #return $array['password']; return $userarray; } catch (PDOException $e) { echo $e->getMessage(); } return false; }
/** * Every method which needs to execute a SQL query uses this method. * * 1. If not connected, connect to the database. * 2. Prepare Query. * 3. Parameterize Query. * 4. Execute Query. * 5. On exception : Write Exception into the log + SQL query. * 6. Reset the Parameters. */ private function Init($query, $parameters = "") { # Connect to database if (!$this->bConnected) { $this->Connect(); } try { # Prepare query $this->sQuery = $this->pdo->prepare($query); # Add parameters to the parameter array $this->bindMore($parameters); // Lista de parametros que podem ser recuperados no log $logParamsList = array(); # Bind parameters if (!empty($this->parameters)) { foreach ($this->parameters as $param) { $parameters = explode("", $param); $this->sQuery->bindParam($parameters[0], $parameters[1]); // Guarda parametros para exibir no log. $logParamsList[$parameters[0]] = $parameters[1]; } } // Adiciona aos logs $this->queryLogs[(string) ++$this->i . ' - ' . mctime()] = array('query' => is_object($query) ? $query->__toString() : $query, 'params' => $logParamsList); # Execute SQL $this->success = $this->sQuery->execute(); } catch (\PDOException $e) { # Write into log and display Exception $this->ExceptionLog($e->getMessage(), $query); throw new \Exception($e->getMessage()); } # Reset the parameters $this->parameters = array(); }