PK

ADDRLIN : /home/questend/public_html/domains/serenatravels.in/
FLL :
Current File : /home/questend/public_html/domains/serenatravels.in/connection.php

<?php

class PDODB{
    private static $_instance = null;
    private $_pdo,      # @object, The PDO object
        $_sQuery,   # @object, PDO statement object
        $_error = false,
        $_log,      # @object, Object for logging exceptions
        $parameters,# @array, The parameters of the SQL query
        $_results,  # @array, The _results of the SQL query
        $_count = 0,
        $_countLimit,
        $_limit,
        $_page;
    public $variables;  # @array, The parameters of the SQL query

    private function __construct($data = array())
    {
        //$this->_log = new Log();
        $this->parameters = array();
        $this->variables = $data;
        // Set DSN
        $dsn = 'mysql:host=localhost;dbname=serena_travels';
        // Set options
        $options = array(
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
            PDO::ATTR_PERSISTENT => true,
            # We can now log any exceptions on Fatal error
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            # Disable emulation of prepared statements, use REAL prepared statements instead.true || false
            PDO::ATTR_EMULATE_PREPARES => true,
            # We set default FETCH_ASSOC array mode 
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        );
        try {            
            $this->_pdo = new PDO($dsn,'root','', $options);
            //$this->_pdo = new PDO($dsn,'questend_usrTruffle','6Lj3WCk92_EaM{qQ)%eBX%Fu', $options);
            
            $this->_pdo->prepare("set session wait_timeout=10000,interactive_timeout=10000,net_read_timeout=10000");
        } catch (PDOException $e) {

            # Write into log and display Exception
            $this->ExceptionLog($e->getMessage());
            die("Error establishing a database connection.");
        }

    }

    public static function getInstance(){   //$status = $conn->getAttribute(PDO::ATTR_CONNECTION_STATUS);
        if (!isset(self::$_instance)) {
            self::$_instance = new PDODB();
        }
        return self::$_instance;
    }

    public static function closeInstance(){
        # Set the PDO object to null to close the connection
        # http://www.php.net/manual/en/pdo.connections.php
        return self::$_instance = null;
    }

    /**
     *    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 = null){  
        // # Connect to database
        // if (!isset(self::$_instance)) {
        //     $this->getInstance();
        // }
        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 => $value) {

                    $type = PDO::PARAM_STR;
                    switch ($value[1]) {
                        case is_int($value[1]):
                            $type = PDO::PARAM_INT;
                            break;
                        case is_bool($value[1]):
                            $type = PDO::PARAM_BOOL;
                            break;
                        case is_null($value[1]):
                            $type = PDO::PARAM_NULL;
                            break;
                    }
                    // Add type when binding the values to the column
                    $this->_sQuery->bindValue($value[0], $value[1], $type);
                }
            }

            # Execute SQL 
            $this->_sQuery->execute();
            //return "Success";
        } catch (PDOException $e) {
            # Write into log and display Exception
            $errorView = $this->ExceptionLog($e->getMessage(), $query);
            //return $errorView;
            //echo (Config::get('debug'))?$errorView:'Some error found !';
            die('');
        }
        # Reset the parameters
        $this->parameters = array();
    }

    /**
     * @void
     *
     *    Add the parameter to the parameter array
     * @param string $para
     * @param string $value
     */
    public function bind($para, $value){
        $this->parameters[sizeof($this->parameters)] = [":" . $para, $value];
    }

    /**
     * @void
     *
     *    Add more parameters to the parameter array
     * @param array $parray
     */
    public function bindMore($parray){
        if (empty($this->parameters) && is_array($parray)) {
            $columns = array_keys($parray);
            foreach ($columns as $i => &$column) {
                $this->bind($column, $parray[$column]);
            }
        }
    }

    /**
     *  If the SQL query  contains a SELECT or SHOW statement it returns an array containing all of the result set row
     *    If the SQL statement is a DELETE, INSERT, or UPDATE statement it returns the number of affected rows
     *
     * @param  string $query
     * @param  array $params
     * @param  int $fetchmode
     * @return mixed
     */
    public function query($query, $params = null){
        $query = trim(str_replace("\r", " ", $query));

        $this->Init($query, $params);

        $rawStatement = explode(" ", preg_replace("/\s+|\t+|\n+/", " ", $query));

        # Which SQL statement is used
        $statement = strtolower($rawStatement[0]);

        if ($statement === 'select' || $statement === 'show' || $statement === 'call') {

            $result = $this->_sQuery->fetchAll();
            /*p($result);
            exit;*/
            $this->_results = $result;
            $this->_count = $this->_sQuery->rowCount();
            $this->_sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued,
            return $result;

        } elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') {

            $result = $this->_sQuery->rowCount();
            $this->_sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued,
            $this->_count = $result;
            return $result;
        } else {
            return NULL;
        }
    }

    public function getPaginationData($query=null, $count=0 ,$limit = 10, $page = 1 ) {
     
        $this->_limit   = $limit;
        $this->_page    = $page;
        $this->_countLimit = $count;
        if(isset($query) && isset($this->_countLimit)){
            $query = trim(str_replace("\r", " ", $query));            
            $this->_countLimit = $count;
            if ( $this->_limit == 'all' ) {                
                $this->Init($query,null);
                $results = $this->_sQuery->fetchAll();
                $this->_results = $results;
                //$this->_count = $this->_sQuery->rowCount();
                $this->_sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued,
               
            } else {   
                $query      = $query." LIMIT " . ( ( $this->_page - 1 ) * $this->_limit ) . ", $this->_limit";
                $this->Init($query,null);
                $results = $this->_sQuery->fetchAll();
                $this->_results = $results;
                //$this->_count = $this->_sQuery->rowCount();
                $this->_sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued,
                
            }

            $result         = [];
            $result['page']  = $this->_page;
            $result['limit']  = $this->_limit;
            $result['total']  = $this->_countLimit;
            $result['data']  = $results;
         
            return $result;
        }
        return false;

    }

    public function getPaginationLinks( $links, $list_class ) {
        if ( $this->_limit == 'all' ) {
            return '';
        }
     
        $last       = ceil( $this->_countLimit / $this->_limit );
     
        $start      = ( ( $this->_page - $links ) > 0 ) ? $this->_page - $links : 1;
        $end        = ( ( $this->_page + $links ) < $last ) ? $this->_page + $links : $last;
     
        $html       = '<ul class="' . $list_class . '">';
     
        $class      = ( $this->_page == 1 ) ? "disabled" : "";
        $html       .= '<li class="' . $class . '"><a href="?limit=' . $this->_limit . '&page=' . ( $this->_page - 1 ) . '">&laquo;</a></li>';
     
        if ( $start > 1 ) {
            $html   .= '<li><a href="?limit=' . $this->_limit . '&page=1">1</a></li>';
            $html   .= '<li class="disabled"><span>...</span></li>';
        }
     
        for ( $i = $start ; $i <= $end; $i++ ) {
            $class  = ( $this->_page == $i ) ? "active" : "";
            $html   .= '<li class="' . $class . '"><a href="?limit=' . $this->_limit . '&page=' . $i . '">' . $i . '</a></li>';
        }
     
        if ( $end < $last ) {
            $html   .= '<li class="disabled"><span>...</span></li>';
            $html   .= '<li><a href="?limit=' . $this->_limit . '&page=' . $last . '">' . $last . '</a></li>';
        }
     
        $class      = ( $this->_page == $last ) ? "disabled" : "";
        $html       .= '<li class="' . $class . '"><a href="?limit=' . $this->_limit . '&page=' . ( $this->_page + 1 ) . '">&raquo;</a></li>';
     
        $html       .= '</ul>';
     
        return $html;
    }

    /**
     *  Returns the last inserted id.
     * @return string
     */
    public function lastInsertId(){
        return $this->_pdo->lastInsertId();
    }

    /**
     * Starts the transaction
     * @return boolean, true on success or false on failure
     */
    public function beginTransaction(){
        return $this->_pdo->beginTransaction();
    }

    /**
     *  Execute Transaction
     * @return boolean, true on success or false on failure
     */
    public function endTransaction(){
        return $this->_pdo->commit();
    }

    /**
     *  Rollback of Transaction
     * @return boolean, true on success or false on failure
     */
    public function cancelTransaction(){
        return $this->_pdo->rollBack();
    }

    /*
    *The Debut Dump Parameters methods dumps the the information that
    *was contained in the Prepared Statement. This method uses the 
    */
    public function debugDumpParams(){
        return $this->_sQuery->debugDumpParams();
    }

    /**
     *    Returns an array which represents a column from the result set
     *
     * @param  string $query
     * @param  array $params
     * @return array
     */
    public function column($query, $params = null){
        $this->Init($query, $params);
        $Columns = $this->_sQuery->fetchAll(PDO::FETCH_NUM);
        $this->_sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued,
        $column = null;

        foreach ($Columns as $cells) {
            $column[] = $cells[0];
        }

        return $column;

    }

    /**
     *    Returns an array which represents a row from the result set
     *
     * @param  string $query
     * @param  array $params
     * @param  int $fetchmode
     * @return array
     */
    public function row($query, $params = null){
        $this->Init($query, $params);
        $result = $this->_sQuery->fetch();
        $this->_results = $result;
        $this->_count = $this->_sQuery->rowCount();
        $this->_sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued,
        return $result;
    }

    /**
     *    Returns the value of one single field/column
     *
     * @param  string $query
     * @param  array $params
     * @return string
     */
    public function single($query, $params = null){  
        $this->Init($query, $params);
        $result = $this->_sQuery->fetchColumn();
        $this->_results = $result;
        $this->_sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued
        return $result;
    }

    /**
     *Returns the value of table column name
     *
     * @param  string $query
     * @param  string $params
     * @param array $customfilds
     * @return string
     */
    public function getColumnNames($query, $params = null, $customfilds = null){

        $this->Init($query, $params);
        $Columns = $this->_sQuery->fetchAll();
        $this->_sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issueds
        try {
            foreach ($Columns as $outer_key => $array) {

                foreach ($array as $inner_key => $value) {

                    if ($inner_key === 'Field') {
                        /*if (!(int)$inner_key){
                            return $this->column_names[] = $value;
                        }*/
                        $column_names[] = $value;
                    }
                }

            }
            if (!empty($customfilds)) {
                if (is_array($customfilds)) {
                    foreach ($customfilds as $key => $value) {
                        $customkeys[] = $key;
                    }
                    return $result = array_intersect($column_names, $customkeys);
                }
            } else {
                return $column_names;
            }

        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }
    }

    /*
     * Create data
     * @tablename string
     * @filds array data
     * @return $mixed
     * */
    public function insert($tablename, $filds = array()){
        $bindings = $filds;//$this->variables;
        try {
            if (!empty($bindings)) {
                $fields = array_keys($bindings);
                $fieldvalues = array_values($bindings);
                $fieldsvals = array(implode(",", $fields), "'" . implode("','", $fieldvalues) . "'");
                $sql = "INSERT INTO " . $tablename . " (" . $fieldsvals[0] . ") VALUES (" . $fieldsvals[1] . ")";
            } else {
                $sql = "INSERT INTO " . $tablename . " () VALUES ()";
            }
            return $this->exec($sql);
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }

    }

    /*
    * update table data
    * @tablename string
    * @filds array data
    * @where array data
    * @return $mixed
    * */
    public function update($tablename,$filds = array(), $where = array()){
        //$this->variables[$this->pk] = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk];

        $fieldsvals = '';
        $columns = $filds;//array_keys($filds);
        try {
            foreach ($columns as $key => $value) {
                //if($key !== $this->pk)
                $value=($value==NULL)?'NULL':"'$value'";
                $fieldsvals .= $key . " = " .$value. ","; //$key . "=".$value.",";
            }
            //echo $fieldsvals;
            if (!empty($where)) {
                $fieldsco = array();
                $columns = array_keys($where);
                foreach ($where as $key => $value) {
                    $value=($value==NULL)?'NULL':"'$value'";
                    $fieldsco [] = $key . " = " .$value;
                }
                $condition = " WHERE " . implode(" AND ", $fieldsco);
            }
            $fieldsvals = substr_replace($fieldsvals, '', -1);

            if (count($columns) >= 1) {

                $sql = "UPDATE " . $tablename . " SET " . $fieldsvals . $condition;
                if (count($where) === "0") {
                    //unset($this->variables[$this->pk]);
                    $sql = "UPDATE " . $tablename . " SET " . $fieldsvals;
                }
                //echo $sql; exit;
                return $this->exec($sql);
            }
            return false;
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }

    }

    /*
     * dalete table data
     * @tablename string   
     * @condition array data
     * @return $mixed
     * */
    public function delete($tablename,$condition = array()){

        try {
            if (!empty($tablename)) {
                if (!empty($condition)) {
                    $fieldsco = array();
                    $columns = array_keys($condition);
                    foreach ($condition as $key => $value) {

                        $fieldsco [] = $key . " = " . "'$value'";

                    }
                    $condition = " WHERE " . implode(" AND ", $fieldsco);
                    $sql = "DELETE FROM " . $tablename . $condition . " LIMIT 1";
                }
            }

            return $this->exec($sql);
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }
    }

    /*
     * find singl row data
     * @tablename string   
     * @condition array data
     * @return $mixed
     * */
    public function find($tablename,$condition=array(),$column=null){

        try {
            //$columvalue = $this->getColumnNames("SHOW COLUMNS FROM $tablename", null, $condition);
            //$column = (empty($column)) ? '*' : $column;
            if (is_array($column)){
                $columnfield = implode(',',$column);      
            }else{
                $columnfield ='*';
            }
            $sql = "SELECT $columnfield FROM $tablename ";

            if (!empty($tablename)) {
                //if (!empty($condition)) {
                    if (!empty($condition)) {
                        $fieldsvals = array();
                        $columns = array_keys($condition);
                        foreach ($columns as $key => $value) {
                            $fieldsvals [] = $value . " =:" . $value;

                        }
                        $sql .= " WHERE " . implode(" AND ", $fieldsvals);
                    }
                    //$result = $this->row("SELECT Id, Age FROM Persons WHERE firstname = :f", array("f"=>"Zoe"));
                    $result = $this->row($sql, $condition);
                    return ($result != false) ? $result : null;
                //}
            }
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }

    }

    /*
     * search all matching data
     * @tablename string   
     * @fields array data
     * @short array data
     * @return $mixed
     * */
    public function search($tablename,$condition=array(),$column=null,$sort=array()){
        try {
            //$column = (empty($column)) ? '*' : $column;
            if (is_array($column)){
                $columnfield = implode(',',$column);      
            }else{
                $columnfield ='*';
            }
            $sql = "SELECT $columnfield FROM $tablename";
            $bindings = empty($condition) ? $this->variables : $condition;

            if (!empty($bindings)) {
                $fieldsvals = array();
                $columns = array_keys($bindings);
                foreach ($bindings as $key => $value) {
                    $fieldsvals [] = $key . " = " . "'$value'";
                }
                $sql .= " WHERE " . implode(" AND ", $fieldsvals);
            }

            if (!empty($sort)) {
                $sortvals = array();
                foreach ($sort as $key => $value) {
                    $sortvals[] = $value; //. " " . $value;
                }
                $sql .= " ORDER BY " . implode(", ", $sortvals)." DESC";
            }
            //echo($sql);//exit;
            return $this->exec($sql);
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }

    }

    /*
     * Read all records
     *
     * @return $mixed
     * */
    public function read($query, $params = null){
        try {
            $this->Init($query, $params);
            $result = $this->_sQuery->fetchall();
            $this->_results = $result;
            $this->_count = $this->_sQuery->rowCount();
            $this->_sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued,

            return $result;

        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }

    }

    public function readjson($query, $params = null){
        try {
            $this->Init($query, $params);
            $result = $this->_sQuery->fetchall();
            $this->_results = $result;
            $this->_count = $this->_sQuery->rowCount();
            $this->_sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued,
            return $result;
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }

    }

    /////////////CUSTOM QUERY//////////////
    public function customQuery($sql, $params = array()){

        $this->_error=false;
        try {
            if ($this->_sQuery=$this->_pdo->prepare($sql)){
                $pos=1;
                if (count($params)) {
                    foreach ($params as $param) {
                        $this->_sQuery->bindValue($pos,$param);
                        $pos++;
                    }
                }

                if ($this->_sQuery->execute()) {
                    $this->_results =$this->_sQuery->fetchAll();//PDO::FETCH_OBJ
                    $this->_count   =$this->_sQuery->rowCount();
                }else{
                    $this->_error=true;
                }
            }
        } catch (Exception $e) {
           $errorView = $this->ExceptionLog($e->getMessage(), $sql);
           echo (Config::get('debug'))?$errorView:'Some error found !';
           die();
        }
        return $this;
    }

    public function action($action,$table,$where=array()){
        if(count($where)===3){
            $operators  = array('=', '>', '<', '>=', '<=', '!=');
            $field      = $where[0];
            $operator   = $where[1];
            $value      = $where[2];

            if(in_array($operator,$operators)) {
                $sql="{$action} FROM {$table} WHERE {$field} {$operator} ?";

                if (!$this->customQuery($sql,array($value))){
                    return $this;
                }
            }
        }
        return false;
    }

    public function get($table,$where){
            return $this->action('SELECT *', $table, $where);
        }
    /////////////CUSTOM QUERY/////////////

    public function all($tablename,$column=null){   
        if (is_array($column)){
            $fieldsvals = implode(',',$column);      
        }else{
            $fieldsvals ='*';
        }
        try{
            return $this->query("SELECT $fieldsvals FROM $tablename");
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }
    }

    /*public function all($tablename,$column=null)
    {   
        try {

            return $this->query("SELECT * FROM " . $tablename);
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }
    }*/

    public function min($field, $tablename){
        try {
            if ($field)
                return $this->single("SELECT min(" . $field . ")" . " FROM " . $tablename);
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }
    }

    public function max($field, $tablename){
        try {
            if ($field)
                return $this->single("SELECT max(" . $field . ")" . " FROM " . $tablename);
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }
    }

    public function maxWhere($field, $tablename, $where){
        try {
            /*$bindings = empty($where) ? $this->variables : $where;

            if (!empty($bindings)) {
                $fieldsvals = array();
                $columns = array_keys($bindings);
                foreach ($bindings as $key => $value) {
                    $fieldsvals [] = $key . " = " . "'$value'";
                }
                $sql .= " WHERE " . implode(" AND ", $fieldsvals);
            }*/
            if ($field)
                return $this->single("SELECT max(" . $field . ")" . " FROM " .$tablename." WHERE ".$where);
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }
    }

    public function avg($field, $tablename){
        try {
            if ($field)
                return $this->single("SELECT avg(" . $field . ")" . " FROM " . $tablename);
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }
    }

    public function sum($field, $tablename){
        try {
            if ($field)
                return $this->single("SELECT sum(" . $field . ")" . " FROM " . $tablename);
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }
    }

    public function countField($field, $tablename){
        try {
            if ($field)
                return $this->single("SELECT count(" . $field . ")" . " FROM " . $tablename);
        } catch (Exception $e) {
            return $e->getMessage(); //return exception
        }
    }

    public function count(){
        return $this->_count;
    }

    public function error(){
        return $this->_error;
    }

    public function results(){
        return $this->_results;
    }

    public function first(){
        return $this->results()[0];
    }

    /**
     * Writes the log and returns the exception
     *
     * @param  string $message
     * @param  string $sql
     * @return string
     */
    private function ExceptionLog($message, $sql = null){
        $exception = 'Unhandled Exception. <br />';
        $exception .= $message;
        $exception .= "<br /> You can find the error back in the log.";

        if (!empty($sql)) {
            # Add the Raw SQL to the Log
            $message .= "\r\nRaw SQL : " . $sql;
        }
        # Write into log
        ///$this->_log->write($message);

        return $exception;
    }

    private function exec($sql, $array = null){

        if ($array !== null) {
            // Get result with the DB object
            $result = $this->query($sql, $array);
        } else {
            // Get result with the DB object
            $result = $this->query($sql, $this->variables);
        }

        // Empty bindings
        $this->variables = array();

        return $result;
    }
}


PK 99
E-SHOP || DASHBOARD
404

Page Not Found

It looks like you found a glitch in the matrix...

← Back to Home