/**
 * Retrieves entries from database.
 *
 * @param object $db
 * @param string $page
 * @param null|string $url
 * @return array|null
 */
function retrieveEntries($db, $page, $url = null)
{
    if (isset($url)) {
        $sql = "SELECT id, page, title, image, entry, created\nFROM entries\nWHERE url=?\nLIMIT 1";
        $stmt = $db->prepare($sql);
        $stmt->execute(array($url));
        $e = $stmt->fetch();
        $fulldisp = 1;
    } else {
        $sql = "SELECT id, page, title, image, entry, url, created\nFROM entries\nWHERE page=?\nORDER BY created DESC";
        $stmt = $db->prepare($sql);
        $stmt->execute(array($page));
        $e = null;
        while ($row = $stmt->fetch()) {
            $e[] = $row;
            $fulldisp = 0;
        }
        if (!is_array($e)) {
            $fulldisp = 1;
            $e = array('title' => 'No Entries Yet', 'entry' => '<a href="/admin.php">Post an entry!</a>');
        }
    }
    array_push($e, $fulldisp);
    return $e;
}
Example #2
0
 /**
  *
  */
 private function newCompany($name, $number, $revenue, $industry, $type, $cName, $cTel, $cAddress1, $cAddress2, $cAddress3, $cPostcode)
 {
     if ($this->databaseConnection()) {
         $query_new_company = $this->db_connection->prepare('INSERT INTO company (name, reg_number, revenue, industry, company_size, contact_name, contact_tel, contact_address_1, contact_address_2, contact_address_3, contact_address_postcode, users_id, company_type) VALUES(:name, :reg_number, :revenue, :industry, :company_size, :contact_name, :contact_tel, :contact_address_1, :contact_address_2, :contact_address_3, :contact_address_postcode, :users_id, :company_type)');
         $query_new_company->bindValue(':name', $name, PDO::PARAM_STR);
         $query_new_company->bindValue(':reg_number', $number, PDO::PARAM_STR);
         $query_new_company->bindValue(':revenue', $revenue, PDO::PARAM_STR);
         $query_new_company->bindValue(':industry', $industry, PDO::PARAM_STR);
         $query_new_company->bindValue(':company_size', $type, PDO::PARAM_STR);
         $query_new_company->bindValue(':contact_name', $cName, PDO::PARAM_STR);
         $query_new_company->bindValue(':contact_tel', $cTel, PDO::PARAM_STR);
         $query_new_company->bindValue(':contact_address_1', $cAddress1, PDO::PARAM_STR);
         $query_new_company->bindValue(':contact_address_2', $cAddress2, PDO::PARAM_STR);
         $query_new_company->bindValue(':contact_address_3', $cAddress3, PDO::PARAM_STR);
         $query_new_company->bindValue(':contact_address_postcode', $cPostcode, PDO::PARAM_STR);
         $query_new_company->bindValue(':users_id', intval(trim($this->userid)), PDO::PARAM_INT);
         $query_new_company->bindValue(':company_type', intval(trim($this->company_type)), PDO::PARAM_INT);
         $query_new_company->execute();
         // We assume if comptype==1 then its a customer therefore user already active
         if ($this->company_type == 2) {
             if ($this->userActiveLevel == 2) {
                 $userActiveLevel = 3;
             } else {
                 $userActiveLevel = 1;
             }
             $query_update_user = $this->db_connection->prepare('UPDATE users SET user_active_lvl = :userActiveLevel WHERE user_id = :user_id');
             $query_update_user->bindValue(':userActiveLevel', intval(trim($userActiveLevel)), PDO::PARAM_INT);
             $query_update_user->bindValue(':user_id', intval(trim($this->userid)), PDO::PARAM_INT);
             $query_update_user->execute();
         }
         $this->newComp_successful = true;
     }
 }
 /**
  *
  *
  * @return String with HTML-Code for Categorycloud
  */
 public function getCatSize($small, $big, $limit)
 {
     $numberofsizes = $big - $small + 1;
     $sql = "SELECT count\n\t \t\t\tFROM categories\n\t \t\t\tWHERE count>0\n\t \t\t\tORDER BY\n        \t\tcount DESC\n  \t\t\t\tLIMIT {$limit}";
     $stmt = $this->_db->prepare($sql);
     $stmt->execute();
     while ($row = $stmt->fetch()) {
         $min = $row['count'];
     }
     $sql = "SELECT min(count) AS min, max(count) AS max \n\t \t\t\tFROM categories \n\t \t\t\tWHERE count != 0";
     $stmt = $this->_db->prepare($sql);
     $stmt->execute();
     $row = $stmt->fetch();
     $max = $row['max'];
     $numberofcounts = $max - $min + 1;
     $quotient = $numberofcounts / $numberofsizes;
     $sql = "SELECT name, count\n\t \t\t\tFROM categories\n\t \t\t\tWHERE count>0\n\t \t\t\tORDER BY\n        \t\tcount DESC\n  \t\t\t\tLIMIT {$limit}";
     $cloudstring = null;
     if ($stmt = $this->_db->prepare($sql)) {
         $stmt->execute();
         while ($row = $stmt->fetch()) {
             $fontsize = $small + floor(($row['count'] - $min) / $quotient);
             $cloudstring .= "<a href=\"\" style=\"font-size:" . $fontsize . "px\" class=\"cloud-link\" title=\"" . $fontsize . "\">" . $row['name'] . "</a> ";
         }
         return $cloudstring;
     }
 }
Example #4
0
 /**
  * Private/protected methods
  */
 protected function getStmt()
 {
     if (!$this->stmt) {
         $this->stmt = $this->connection->prepare($this->sqlQuery);
     }
     return $this->stmt;
 }
 /**
  * Prepares the list for iteration, creating an empty_dataset if no
  * data set has been registered then calling the dataset reset
  * method.
  * 
  * @see empty_dataset
  * @return void 
  * @access protected 
  */
 function prepare()
 {
     if (empty($this->dataset)) {
         $this->register_dataset(new empty_dataset());
     }
     $this->dataset->prepare();
     $this->show_separator = false;
 }
Example #6
0
 /**
  * Executes an SQL statement
  *
  * @param string $sql
  * @param array $inputParameters
  *
  * @return object returning a result set as a PDOStatement object
  */
 public function query($sql, $inputParameters = [])
 {
     if (!$this->isConnected) {
         $this->connect();
     }
     $sth = $this->dbh->prepare($sql);
     $sth->execute($inputParameters);
     return $sth;
 }
 public function Add_Locations($lat, $long, $userid)
 {
     if ($this->databaseConnection()) {
         $query_to_add_in_db = $this->db_connection->prepare('INSERT INTO location ( latitude  , longitude , uid , time   ) VALUES ( :lat , :long , :userid , now())');
         $query_to_add_in_db->bindValue(':lat', $lat, PDO::PARAM_STR);
         $query_to_add_in_db->bindValue(':long', $long, PDO::PARAM_STR);
         $query_to_add_in_db->bindValue(':userid', $userid, PDO::PARAM_STR);
         $query_to_add_in_db->execute();
     }
 }
 /**
  * Sends a database query to SQL server.
  *
  * @param	string	$res
  * @param	array	$bind 		
  * @return	integer	
  */
 public function query($res, $bind = array())
 {
     $query = null;
     $query = $this->conn->prepare($res);
     if (is_array($bind) && !empty($bind)) {
         $query->execute($bind);
     } else {
         $query->execute();
     }
     return $query;
 }
Example #9
0
 public function insert(\Animals\AnimalAbstract $object)
 {
     if (get_class($object) === 'Animals\\Cat') {
         $animal = 'cats';
     } elseif (get_class($object) === 'Animals\\Dog') {
         $animal = 'dogs';
     } else {
         throw new \Exception('We don\'t know this type of animal (' . get_class($object));
     }
     $sql = sprintf('INSERT INTO `animals` (`animal`,`name`,`age`,`favoriteFood`) VALUES (\'%s\', \'%s\', \'%s\', \'%s\');', $animal, $object->getName(), $object->getAge(), $object->getFavoriteFood());
     $statement = $this->db->prepare($sql);
     return $statement instanceof \PDOStatement ? $statement->execute() : false;
 }
 /**
  * Insert data in database with currentdate and time
  * @author Jim Ahlstrand
  * @return int Id of inserted row
  */
 private function insertComment()
 {
     // Prepare variables
     $date = $this->date->format("Y-m-d H:i:s");
     $subcomments = serialize($this->subcomments);
     $sth = $this->dbh->prepare(SQL_INSERT_COMMENT);
     $sth->bindParam(":user", $this->user, PDO::PARAM_INT);
     $sth->bindParam(':date', $date, PDO::PARAM_STR);
     $sth->bindParam(":data", $this->data, PDO::PARAM_STR);
     $sth->bindParam(":subcomments", $subcomments, PDO::PARAM_STR);
     $sth->execute();
     return $this->dbh->lastInsertId();
 }
Example #11
0
 /**
  * handles the Addition of new user
  */
 public function AddNewUser($userId, $userFirstName, $userLastName, $userPassword, $userPasswordRepeat)
 {
     $userId = trim($userId);
     if (empty($userId)) {
         echo "UserId field is empty";
     }
     if (empty($userFirstName)) {
         echo "User First name field is empty";
     }
     if (empty($userLastName)) {
         echo "User Last name field is empty";
     } elseif (empty($userPassword) || empty($userPasswordRepeat)) {
         echo "Password field is empty";
     } elseif ($userPassword !== $userPasswordRepeat) {
         echo "Passwords are not the same";
     } elseif (strlen($userPassword) < 6) {
         echo "Password has a minimum length of 6 characters";
     } elseif (strlen($userId) < 2) {
         echo "Username cannot be shorter than 2";
     } elseif (!preg_match('/^[a-z\\d]{2}$/i', $userId)) {
         echo "Only a-Z and numbers are allowed";
     } else {
         if ($this->databaseConnection()) {
             // check if username already exists
             $query_check_user_name = $this->db_connection->prepare('SELECT userId FROM users WHERE userId=:userId');
             $query_check_user_name->bindValue(':userId', $userId, PDO::PARAM_STR);
             $query_check_user_name->execute();
             $result = $query_check_user_name->fetchAll();
             // check if usernId exist in the database
             if (count($result) > 0) {
                 for ($i = 0; $i < count($result); $i++) {
                     echo "UserId is already taken.";
                 }
             } else {
                 $userPasswordMd5 = md5($userPassword);
                 // write new users data into database
                 $query_new_user_insert = $this->db_connection->prepare('INSERT INTO users (userId, userFirstName, userLastName, userPassword, userDateCreated) VALUES (:userId, :userFirstName, :userLastName, :userPassword, now())');
                 $query_new_user_insert->bindValue(':userId', $userId, PDO::PARAM_STR);
                 $query_new_user_insert->bindValue(':userFirstName', $userFirstName, PDO::PARAM_STR);
                 $query_new_user_insert->bindValue(':userLastName', $userLastName, PDO::PARAM_STR);
                 $query_new_user_insert->bindValue(':userPassword', $userPasswordMd5, PDO::PARAM_STR);
                 $query_new_user_insert->execute();
                 if (!$query_new_user_insert) {
                     echo "Registration failed. Please go back and try again";
                 } else {
                     echo "Registered!";
                 }
             }
         }
     }
 }
Example #12
0
 /**
  * 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;
 }
 /**
  * handles the entire registration process. checks all error possibilities
  * and creates a new user in the database if everything is fine
  */
 private function registerNewUser()
 {
     if (empty($_POST['user_name'])) {
         $this->errors[] = "Empty Username";
     } elseif (empty($_POST['user_password_new']) || empty($_POST['user_password_repeat'])) {
         $this->errors[] = "Empty Password";
     } elseif ($_POST['user_password_new'] !== $_POST['user_password_repeat']) {
         $this->errors[] = "Password and password repeat are not the same";
     } elseif (strlen($_POST['user_password_new']) < 6) {
         $this->errors[] = "Password has a minimum length of 6 characters";
     } elseif (strlen($_POST['user_name']) > 64 || strlen($_POST['user_name']) < 2) {
         $this->errors[] = "Username cannot be shorter than 2 or longer than 64 characters";
     } elseif (!preg_match('/^[a-z\\d]{2,64}$/i', $_POST['user_name'])) {
         $this->errors[] = "Username does not fit the name scheme: only a-Z and numbers are allowed, 2 to 64 characters";
     } elseif (empty($_POST['user_email'])) {
         $this->errors[] = "Email cannot be empty";
     } elseif (strlen($_POST['user_email']) > 64) {
         $this->errors[] = "Email cannot be longer than 64 characters";
     } elseif (!filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL)) {
         $this->errors[] = "Your email address is not in a valid email format";
     } elseif (!empty($_POST['user_name']) && strlen($_POST['user_name']) <= 64 && strlen($_POST['user_name']) >= 2 && preg_match('/^[a-z\\d]{2,64}$/i', $_POST['user_name']) && !empty($_POST['user_email']) && strlen($_POST['user_email']) <= 64 && filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL) && !empty($_POST['user_password_new']) && !empty($_POST['user_password_repeat']) && $_POST['user_password_new'] === $_POST['user_password_repeat']) {
         // create a database connection
         try {
             $this->db_connection = DBConnect::getConnection();
         } catch (Exception $e) {
             $this->errors[] = $e->getMessage();
             return;
         }
         // remove everything that could be (html/javascript-) code
         $user_name = strip_tags($_POST['user_name'], ENT_QUOTES);
         $user_email = strip_tags($_POST['user_email'], ENT_QUOTES);
         $user_password = $_POST['user_password_new'];
         // crypt the user's password with PHP 5.5's password_hash() function, results in a 60 character
         // hash string. the PASSWORD_DEFAULT constant is defined by the PHP 5.5, or if you are using
         // PHP 5.3/5.4, by the password hashing compatibility library
         $user_password_hash = password_hash($user_password, PASSWORD_DEFAULT);
         $user_exists_statement = $this->db_connection->prepare("SELECT user_id FROM users WHERE user_name = :user_name OR user_email = :user_email");
         $user_exists_statement->execute(array('user_name' => $user_name, 'user_email' => $user_email));
         if ($user_exists_statement->rowCount() > 0) {
             $this->errors[] = "Sorry, that username / email address is already taken.";
         } else {
             $insert_user_statement = $this->db_connection->prepare("\r\n                  INSERT INTO users (user_name, user_password_hash, user_email)\r\n                  VALUES (:user_name, :user_password_hash, :user_email)\r\n                ");
             $insert_user_statement->execute(array('user_name' => $user_name, 'user_password_hash' => $user_password_hash, 'user_email' => $user_email));
             $this->messages[] = "Your account has been created successfully. You can now log in.";
         }
     } else {
         $this->errors[] = "An unknown error occurred.";
     }
 }
Example #14
0
 /**
  * @void
  *
  * All database query call use this method, before retriev result
  * This method do:
  * 1. Prepare the query statements.
  * 2. Use bindParam to catch the query statement's parameter.
  * 3. Execute the query.
  *
  * @param string $query
  * @param string $parameters
  */
 private function init($query, $parameters = '')
 {
     if (!$this->connected) {
         $this->connect();
     }
     $success = false;
     try {
         // Prepare statement
         $this->queryStatement = $this->pdo->prepare($query);
         // Save last prepared statement
         $this->lastQuery = $this->queryStatement;
         // Bind each values
         $this->bindMore($parameters);
         if (!empty($this->parameters)) {
             foreach ($this->parameters as $param) {
                 $parameters = explode('[---]', $param);
                 $this->queryStatement->bindParam($parameters[0], $parameters[1]);
             }
         }
         $this->queryStatement->execute();
         $success = true;
     } catch (\PDOException $e) {
         # Write into log
         $this->error = $this->errorMessage($e);
         $this->exceptionLog($e);
     }
     // Reset the parameters
     $this->parameters = array();
     return $success;
 }
Example #15
0
 /**
  * Used to normalize string before passing
  * it to detectors
  *
  * @param   array   $data
  * @return  string
  */
 protected function prepareData(array $data)
 {
     $data = array_merge(array('name' => null, 'email' => null, 'username' => null, 'id' => null, 'text' => null, 'ip' => $this->getIp(), 'user_agent' => $this->getUserAgent()), $data);
     $data['original_text'] = $data['text'];
     $data['text'] = $this->stringProcessor ? $this->stringProcessor->prepare($data['text']) : $data['text'];
     return $data;
 }
Example #16
0
 /**
  * Method for getting all the records of a table.
  *
  * @return array Model
  */
 public function getAll()
 {
     $aModels = array();
     $sQuery = "select *\n                   from " . $this->_sTable . " ";
     if (isset($this->_sId)) {
         $sQuery .= "where " . $this->_sIdColumn . " like CONVERT(:sId USING utf8) COLLATE utf8_bin";
     }
     $sQuery .= ";";
     try {
         $oStmt = $this->_pPDO->prepare($sQuery);
         $oStmt->bindParam(':sId', $this->_sId, \PDO::PARAM_STR);
         $oStmt->execute();
         $i = 0;
         foreach ($oStmt->fetchAll(\PDO::FETCH_ASSOC) as $aRow) {
             $aModels[$i] = new Model($this->_sTable, $this->_sIdColumn, $aRow[$this->_sIdColumn], false);
             foreach ($aRow as $sKey => $sValue) {
                 $aModels[$i]->{$sKey} = $sValue;
             }
             $aModels[$i]->fillLoadedData();
             $i++;
         }
     } catch (\PDOException $e) {
         $e->getMessage();
     }
     return $aModels;
 }
Example #17
0
 /**
  * Executes a SQL query.
  *
  * Values for the query can either be an array as the second argument or
  * multiple arguments in the method.
  *
  * @access public
  * @static
  * @param string $query The query to be run
  * @param array $values Optional The values of the query
  * @return mixed
  */
 public static function execute($query, $values = array())
 {
     if (!is_array($values)) {
         $values = func_get_args();
         array_shift($values);
         // first argument is the sql query
     }
     // fix operators in query
     $query = self::fixOperators($query, $values);
     // prepare the statement and get it ready to be executed
     $statement = self::$pdo->prepare($query);
     if (Reg::get('Database.viewQueries')) {
         echo '<pre>';
         var_dump(array($query, $values));
         echo '</pre>';
     }
     // execute the query
     if ($statement->execute($values) === false) {
         // handle the error
         $error = $statement->errorInfo();
         throw new EvergreenException('MODEL_DB_FAILURE', array('trace' => $error, 'errorMessage' => end($error), 'errorId' => isset($error[1]) ? $error[1] : 0, 'query' => $query, 'queryValues' => $values));
     } else {
         // store a count of the queries
         self::$queryCount += 1;
         if (Reg::get('Database.storeQueries') == true) {
             // store the query
             self::$queries[] = array($query, $values);
         }
         // set the default fetch mode for the query
         $statement->setFetchMode(PDO::FETCH_ASSOC);
         return $statement;
     }
     return false;
 }
Example #18
0
 /**
  * Prepare and execute query.
  *
  * @param string $sql     SQL string to query.
  * @param array  $params  Omit to do a normal query instead of a PDO prepared query.
  *
  * @return resource
  */
 public function query($sql, $params = null)
 {
     if (!$params) {
         $this->resultset = $this->dbh->query($sql);
     } else {
         $stmt = $this->dbh->prepare($sql);
         if (!empty($params)) {
             foreach ($params as $column => $param) {
                 if (is_int($params[$column])) {
                     $type = PDO::PARAM_INT;
                 } else {
                     if (is_null($params[$column]) || $params[$column] === null) {
                         $type = PDO::PARAM_NULL;
                     } else {
                         $type = PDO::PARAM_STR;
                     }
                 }
                 $stmt->bindValue(':' . $column, $params[$column], $type);
             }
         }
         $stmt->execute();
         $this->resultset = $stmt;
         if ($this->debug) {
             var_dump($params);
         }
     }
     if ($this->debug) {
         echo '<strong style="color: #dd0000;">' . $sql . '</strong> :: ' . implode(', ', $this->dbh->errorInfo()) . '<br /><br />';
     }
     return $this->resultset;
 }
 public function Show_Device($Data, $Type)
 {
     if ($this->databaseConnection()) {
         if ($Type == 0) {
             $query_to_search_user = $this->db_connection->prepare('SELECT * FROM police_directory WHERE email_id = :data ');
         } else {
             $query_to_search_user = $this->db_connection->prepare('SELECT * FROM police_directory WHERE phone_number = :data');
         }
         $query_to_search_user->bindValue(':data', $Data, PDO::PARAM_STR);
         $query_to_search_user->execute();
         if ($results_police_data = $query_to_search_user->fetchObject()) {
             $this->Police_Information[0] = $results_police_data->id;
             $this->Police_Information[1] = $results_police_data->first_name;
             $this->Police_Information[2] = $results_police_data->middle_name;
             $this->Police_Information[3] = $results_police_data->last_name;
             $this->Police_Information[4] = $results_police_data->gcm_key;
             $police_id = $results_police_data->id;
             // Code to get latitude and longitude
             $query_to_get_location = $this->db_connection->prepare('SELECT latitude , longitude FROM location WHERE uid = :id ORDER BY id DESC LIMIT 1');
             $query_to_get_location->bindValue(':id', $police_id, PDO::PARAM_STR);
             $query_to_get_location->execute();
             if ($results_location = $query_to_get_location->fetchObject()) {
                 $this->Police_Information[5] = $results_location->latitude;
                 $this->Police_Information[6] = $results_location->longitude;
             }
             $this->flag = true;
         } else {
             $this->Police_Information[0] = "Result is not found . Please Try Again .";
         }
     }
 }
Example #20
0
 /**
  * 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;
 }
Example #21
0
 /**
  * Tests for existing tables with the same prefix
  *
  * @since 6.4.0.13
  *
  * @return void
  */
 function test_prefix()
 {
     // Make sure we've already connected. This should never be true.
     if (empty($this->tests['connect'])) {
         $this->test_connect();
     }
     // WordPress tables exist matching prefix?
     $prefix_exists_sql = $this->wpdb->prepare("SHOW TABLES LIKE '%s';", str_replace('_', '\\_', $this->creds['prefix']) . "%");
     $result = $this->wpdb->get_results($prefix_exists_sql);
     if (empty($result)) {
         // WordPress prefix does not exist
         $this->tests['prefix_exists'] = false;
     }
     // Make sure prefix meets wp standards
     if (!preg_match('|[^a-z0-9_]|i', $this->creds['prefix'])) {
         // Prefix meets WP standards
         $this->tests['prefix'] = true;
         if (preg_match('/^[a-z0-9]+_$/i', $this->creds['prefix'])) {
             // Prefix passes with no warning.
             $this->tests['prefix_warn'] = false;
         } else {
             $this->tests['prefix_warn'] = true;
         }
     }
 }
Example #22
0
File: PDO.php Project: b091/mkphp-1
 /**
  * Odczytanie kolejnej wartości sekwencji (inkrementowanej w bazie danych)
  *
  * @param String     $sequence - nazwa sekwencji
  *
  * @throws MK_Db_Exception
  * @return Float/Integer
  */
 function setNextVal($sequence)
 {
     // Przygotowanie zapytania SQL
     $sql = "SELECT nextval('{$sequence}')";
     $pdoObj = $this->db->prepare($sql);
     // Ustawienie tablicy asocjacyjnej w odpowiedzi
     $pdoObj->setFetchMode(PDO::FETCH_ASSOC);
     // Wykonanie zapytania SQL
     if ($pdoObj->execute() === false) {
         throw new MK_Db_Exception(MK_Db_PDO_Singleton::MESSAGE_ERROR_RESULTS);
     }
     // Odczytanie odpowiedzi (array)
     $resValue = $pdoObj->fetchColumn();
     // Jeżeli odpowiedź będzie false, to operacja powinna być wstrzymana,
     // ponieważ wartość sekwencji jest nieprawidłowa przez co dane zostałyby
     // zapisane w bazie danych w nieodpowiedni sposób.
     if ($resValue === false) {
         throw new MK_Db_Exception(MK_Db_PDO_Singleton::MESSAGE_ERROR_SEQUENCE);
     }
     // Zwrócenie szczegółowego komunikatu w konsoli FireBug-a
     if (MK_DEBUG_FIREPHP) {
         $this->fireBugSqlDump("setNextVal", $sql);
     }
     // Jeżeli jest włączone debugowanie, to SQL-e zapisywane są do pliku debug.log
     $this->debugToFile($sql);
     return $resValue;
 }
 /**
  * Method attempts to prepare the SQL query
  * and throws an error if there was a problem.
  */
 protected function _prepareQuery()
 {
     if (!($stmt = $this->_mysqli->prepare($this->_query))) {
         trigger_error("Problem preparing query ({$this->_query}) " . $this->_mysqli->error, E_USER_ERROR);
     }
     return $stmt;
 }
Example #24
0
 /**
  * bindParam()
  *
  * @access public
  * @param  string $sQuery
  * @param  array  $aryParams
  * @return mixed             string | PEAR_Error
  */
 function bindParam($sQuery, $aryParams)
 {
     $objStatement = $this->_objWork->prepare($sQuery);
     $objStatement->bindValueArray($aryParams);
     $sRealquery = '';
     $iLastPosition = 0;
     foreach ($objStatement->positions as $iCurrentPosition => $sParameter) {
         if (!array_key_exists($sParameter, $objStatement->values)) {
             return PEAR::raiseError(null, MDB2_ERROR_NOT_FOUND, null, null, 'Unable to bind to missing placeholder: ' . $sParameter, __FUNCTION__);
         }
         $sValue = $objStatement->values[$sParameter];
         $sRealquery .= substr($sQuery, $iLastPosition, $iCurrentPosition - $iLastPosition);
         if ('' == $sValue) {
             $sValueQuoted = 'NULL';
         } else {
             $sValueQuoted = $this->_objWork->quote($sValue);
             if (PEAR::isError($sValueQuoted)) {
                 return $sValueQuoted;
             }
         }
         $sRealquery .= $sValueQuoted;
         $iLastPosition = $iCurrentPosition + 1;
     }
     $sRealquery .= substr($sQuery, $iLastPosition);
     $objStatement->free();
     return $sRealquery;
 }
Example #25
0
 /**
  * Resets a user's status to unverified and sends them an email
  *
  * @return mixed    TRUE on success and a message on failure
  */
 public function resetPassword()
 {
     $sql = "UPDATE users\n                SET verified=0\n                WHERE Email=:email\n                LIMIT 1";
     try {
         $stmt = $this->_db->prepare($sql);
         $stmt->bindParam(":email", $_POST['e'], PDO::PARAM_STR);
         $stmt->execute();
         $stmt->closeCursor();
     } catch (PDOException $e) {
         return $e->getMessage();
     }
     $sql = "SELECT ver_code\n                FROM users\n                WHERE Email=:email\n                LIMIT 1";
     try {
         $stmt = $this->_db->prepare($sql);
         $stmt->bindParam(":email", $_POST['e'], PDO::PARAM_STR);
         $stmt->execute();
         $row = $stmt->fetch();
         $v = $row["ver_code"];
         $stmt->closeCursor();
     } catch (PDOException $e) {
         return $e->getMessage();
     }
     $sendgrid = new SendGrid($_ENV['SG_KEY']);
     $mail = new SendGrid\Email();
     try {
         $sendgrid->send($this->sendResetEmail($_POST['e'], $v, $mail));
     } catch (\SendGrid\Exception $e) {
         echo $e->getCode();
         foreach ($e->getErrors() as $er) {
             echo $er;
         }
         return "Sending the email failed!";
     }
     return TRUE;
 }
Example #26
0
 /**
  * 执行操作的底层接口
  *
  * @param string $sql
  * @param array $params
  * @return PDO Statement
  */
 protected function _autoExecute($sql, $params = array())
 {
     try {
         $this->_getChoiceDbConnect();
         if (!$this->_db) {
             exit('DB connection lost.');
         }
         // 调试模式打印SQL信息
         $explain = array();
         if (Com_Db::enableLogging() && DEBUG_EXPLAIN_SQL) {
             $explain = $this->_explain($sql, $params);
         }
         $sqlStartTime = microtime(true);
         // 预编译 SQL
         $stmt = $this->_db->prepare($sql);
         if (!$stmt) {
             exit(implode(',', $this->_db->errorInfo()));
         }
         // 绑定参数
         $params = $params ? (array) $params : array();
         // 执行 SQL
         if (!$stmt->execute($params)) {
             exit(implode(',', $stmt->errorInfo()));
         }
         $sqlCostTime = microtime(true) - $sqlStartTime;
         // 调试模式打印SQL信息
         if (Com_Db::enableLogging()) {
             Com_Db::sqlLog($this->_formatLogSql($sql, $params), $sqlCostTime, $explain);
         }
         return $stmt;
     } catch (Exception $e) {
         Com_Db_Exception::process($e, '[SQL Failed]', $this->_formatLogSql($sql, $params));
         return false;
     }
 }
Example #27
0
 /**
  * List all files related to this folder
  *
  * @return array
  */
 public function fichiers()
 {
     // On prépare la liste des tâches
     $fichiers = array();
     // On fait la liste des événements pour récupérer la liste des tâches
     // correspondantes à chaque événement
     $evenements = $this->evenements();
     // Pour chaque événement, on cherche les tâches
     foreach ($evenements as $evenement) {
         // On prépare la requête
         $sql = 'SELECT *
                 FROM `fichiers`
                 WHERE `interaction_id` = :historique';
         $query = $this->_link->prepare($sql);
         $query->bindParam(':historique', $evenement['historique_id']);
         // On exécute la requête
         $query->execute();
         // On ajoute les informations à la table
         if ($query->rowCount()) {
             $fichiers = array_merge($fichiers, $query->fetchAll(PDO::FETCH_ASSOC));
         }
     }
     // On retourne la liste des tâches
     return $fichiers;
 }
Example #28
0
 public function addFeedback($q1, $q2, $q3, $q4, $q5, $q6, $workshop)
 {
     if ($this->databaseConnection()) {
         $query_to_add_in_db = $this->db_connection->prepare('INSERT INTO 
                       feedback (quest1 , quest2 , quest3 , quest4 ,quest5 ,quest6 , workshop) 
                       VALUES (:q1 , :q2 , :q3 , :q4 , :q5 , :q6, :q7)');
         $query_to_add_in_db->bindValue(':q1', $q1, PDO::PARAM_STR);
         $query_to_add_in_db->bindValue(':q2', $q2, PDO::PARAM_STR);
         $query_to_add_in_db->bindValue(':q3', $q3, PDO::PARAM_STR);
         $query_to_add_in_db->bindValue(':q4', $q4, PDO::PARAM_STR);
         $query_to_add_in_db->bindValue(':q5', $q5, PDO::PARAM_STR);
         $query_to_add_in_db->bindValue(':q6', $q6, PDO::PARAM_STR);
         $query_to_add_in_db->bindValue(':q7', $workshop, PDO::PARAM_STR);
         $query_to_add_in_db->execute();
     }
 }
 /**
  * Constructor
  *
  * Creates prepared statements with acquire bindings.
  *
  * @access private
  */
 private function __construct()
 {
     $this->_db = CoreDB::init();
     $this->_stmt[self::ST_SEL] = $this->_db->prepare(sprintf("\n            SELECT\n                `value`\n            FROM\n                %s\n            WHERE\n                `key` = :key", TBL_CONFIG));
     $this->_stmt[self::ST_DB] = $this->_db->prepare(sprintf("\n            REPLACE\n                %s\n            SET\n                `key` = :key,\n                `value` = :value", TBL_CONFIG));
     $this->_stmt[self::ST_DEL] = $this->_db->prepare(sprintf("\n            DELETE FROM\n                %s\n            WHERE\n                `key` = :key", TBL_CONFIG));
 }
Example #30
0
   /**
    *  Inserts or updates (if exists) a record in the database.
    *
    *  @param string $table        The table containing the record to be inserted.
    *  @param array $data          An array containing the data to be inserted. Format
    *                              should be as follows:
    *                              array('column_name' => 'column_value');
    *  @access public
    *  @return bool 
    */
    public function upsert($table, $data) {
        $sql = 'INSERT INTO `' . $table . '` ';

        $key_names = array_keys($data);
    	$fields = '`' . implode('`, `', $key_names) . '`';
        $values = ':' . implode(', :', $key_names);

    
        $sql .= '(' . $fields . ') VALUES (' . $values . ') ON DUPLICATE KEY UPDATE ';

    	foreach ( $key_names as $name ) {
            $sql .= '`' . $name . '`=:' . $name . ', ';
    	}

        $sql = rtrim($sql, ', ');
    	$statement = $this->_dbh->prepare($sql);

        try {
            $statement->execute($data);
    	} catch ( \PDOException $e ) {
            echo 'An error occurred: ' . $e->getMessage();
            echo '<br /><br />Traceback:<pre>';
            echo var_dump($e->getTrace());
            die('</pre>');
        }

    	$this->_affected_rows = $statement->rowCount();
        return true; 
    }