Advertisement
Guest User

Database.php

a guest
Mar 23rd, 2016
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 15.85 KB | None | 0 0
  1. <?php
  2. /**
  3.  * PDO mysql database helper class
  4.  *
  5.  * @author wildantea <wildannudin@gmail.com>
  6.  * @copyright june 2013
  7.  */
  8. class Database {
  9.  
  10.     protected $pdo;
  11.  
  12.     public $type_db;
  13.  
  14.      public function __construct($type)
  15.     {
  16.         try {
  17.             if ($type=='mysql') {
  18.                   $this->pdo = new PDO($type.":host=".HOST.":".PORT.";dbname=".DATABASE_NAME, DB_USERNAME, DB_PASSWORD );
  19.      
  20.             } else {
  21.                   $this->pdo = new PDO($type.":host=".PG_HOST.";port=".PG_PORT.";dbname=".PG_DATABASE_NAME.";user=".PG_DB_USERNAME.";password=".PG_DB_PASSWORD );
  22.      
  23.             }
  24.         $this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  25.         }
  26.         catch( PDOException $e ) {
  27.             echo "error ". $e->getMessage();
  28.         }
  29.     }
  30.  
  31.  
  32.    /* public function __construct($type)
  33.     {
  34.         $this->type_db = $type;
  35.         try {
  36.             if ($this->type=='mysql') {
  37.                   $this->pdo = new PDO($this->type_db.":host=".HOST.":".PORT.";dbname=".DATABASE_NAME, DB_USERNAME, DB_PASSWORD );
  38.      
  39.             } else {
  40.                   $this->pdo = new PDO($this->type_db.":host=".PG_HOST.";port=".PG_PORT.";dbname=".PG_DATABASE_NAME.";user=".PG_DB_USERNAME.";password=".PG_DB_PASSWORD );
  41.      
  42.             }
  43.         $this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  44.         }
  45.         catch( PDOException $e ) {
  46.             echo "error ". $e->getMessage();
  47.         }
  48.     }*/
  49.  
  50.     /**
  51.     * custom query , joining multiple table, aritmathic etc
  52.     * @param  string $sql  custom query
  53.     * @param  array $data associative array
  54.     * @return array  recordset
  55.     */
  56.     public function fetch_custom( $sql,$data=null) {
  57.         if ($data!==null) {
  58.         $dat=array_values($data);
  59.         }
  60.         $sel = $this->pdo->prepare( $sql );
  61.         if ($data!==null) {
  62.             $sel->execute($dat);
  63.         } else {
  64.             $sel->execute();
  65.         }
  66.         $sel->setFetchMode( PDO::FETCH_OBJ );
  67.         return $sel;
  68.  
  69.     }
  70.  
  71.  
  72.  
  73.     /**
  74.     * fetch only one row
  75.     * @param  string $table table name
  76.     * @param  string $col condition column
  77.     * @param  string $val value column
  78.     * @return array recordset
  79.     */
  80.     public function fetch_single_row($table,$col,$val)
  81.     {
  82.         $nilai=array($val);
  83.         $sel = $this->pdo->prepare("SELECT * FROM $table WHERE $col=?");
  84.         $sel->execute($nilai);
  85.         $sel->setFetchMode( PDO::FETCH_OBJ );
  86.         $obj = $sel->fetch();
  87.         return $obj;
  88.     }
  89.  
  90.     public function fetch_custom_single($sql,$data=null)
  91.     {
  92.         if ($data!==null) {
  93.         $dat=array_values($data);
  94.         }
  95.         $sel = $this->pdo->prepare( $sql );
  96.         if ($data!==null) {
  97.             $sel->execute($dat);
  98.         } else {
  99.             $sel->execute();
  100.         }
  101.         $sel->setFetchMode( PDO::FETCH_OBJ );
  102.          $obj = $sel->fetch();
  103.         return $obj;
  104.     }
  105.  
  106.     /**
  107.     * fetch all data
  108.     * @param  string $table table name
  109.     * @return array recordset
  110.     */
  111.     public function fetch_all($table)
  112.     {
  113.         $sel = $this->pdo->prepare("SELECT * FROM $table");
  114.         $sel->execute();
  115.         $sel->setFetchMode( PDO::FETCH_OBJ );
  116.         return $sel;
  117.     }
  118.     /**
  119.     * fetch multiple row
  120.     * @param  string $table table name
  121.     * @param  array $dat specific column selection
  122.     * @return array recordset
  123.     */
  124.     public function fetch_col($table,$dat)
  125.     {
  126.         if( $dat !== null )
  127.         $cols= array_values( $dat );
  128.         $col=implode(', ', $cols);
  129.         $sel = $this->pdo->prepare("SELECT $col from $table");
  130.         $sel->execute();
  131.         $sel->setFetchMode( PDO::FETCH_OBJ );
  132.         return $sel;
  133.     }
  134.  
  135.     /**
  136.     * fetch row with condition
  137.     * @param  string $table table name
  138.     * @param  array $col which columns name would be select
  139.     * @param  array $where what column will be the condition
  140.     * @return array recordset
  141.     */
  142.     public function fetch_multi_row($table,$col,$where)
  143.     {
  144.  
  145.         $data = array_values( $where );
  146.         //grab keys
  147.         $cols=array_keys($where);
  148.         $colum=implode(', ', $col);
  149.         foreach ($cols as $key) {
  150.           $keys=$key."=?";
  151.           $mark[]=$keys;
  152.         }
  153.  
  154.         $jum=count($where);
  155.         if ($jum>1) {
  156.             $im=implode('? and  ', $mark);
  157.              $sel = $this->pdo->prepare("SELECT $colum from $table WHERE $im");
  158.         } else {
  159.           $im=implode('', $mark);
  160.              $sel = $this->pdo->prepare("SELECT $colum from $table WHERE $im");
  161.         }
  162.         $sel->execute( $data );
  163.         $sel->setFetchMode( PDO::FETCH_OBJ );
  164.         return  $sel;
  165.     }
  166.  
  167.     /**
  168.     * check if there is exist data
  169.     * @param  string $table table name
  170.     * @param  array $dat array list of data to find
  171.     * @return true or false
  172.     */
  173.     public function check_exist($table,$dat) {
  174.  
  175.         $data = array_values( $dat );
  176.        //grab keys
  177.         $cols=array_keys($dat);
  178.         $col=implode(', ', $cols);
  179.  
  180.         foreach ($cols as $key) {
  181.           $keys=$key."=?";
  182.           $mark[]=$keys;
  183.         }
  184.  
  185.         $jum=count($dat);
  186.         if ($jum>1) {
  187.             $im=implode(' and  ', $mark);
  188.              $sel = $this->pdo->prepare("SELECT $col from $table WHERE $im");
  189.         } else {
  190.           $im=implode('', $mark);
  191.              $sel = $this->pdo->prepare("SELECT $col from $table WHERE $im");
  192.         }
  193.         $sel->execute( $data );
  194.         $sel->setFetchMode( PDO::FETCH_OBJ );
  195.         $jum=$sel->rowCount();
  196.         if ($jum>0) {
  197.             return true;
  198.         } else {
  199.             return false;
  200.         }
  201.     }
  202.     /**
  203.     * search data
  204.     * @param  string $table table name
  205.     * @param  array $col   column name
  206.     * @param  array $where where condition
  207.     * @return array recordset
  208.     */
  209.     public function search($table,$col,$where) {
  210.         $data = array_values( $where );
  211.         foreach ($data as $key) {
  212.            $val = '%'.$key.'%';
  213.            $value[]=$val;
  214.         }
  215.        //grab keys
  216.         $cols=array_keys($where);
  217.         $colum=implode(', ', $col);
  218.  
  219.         foreach ($cols as $key) {
  220.           $keys=$key." LIKE ?";
  221.           $mark[]=$keys;
  222.         }
  223.         $jum=count($where);
  224.         if ($jum>1) {
  225.             $im=implode(' OR  ', $mark);
  226.              $sel = $this->pdo->prepare("SELECT $colum from $table WHERE $im");
  227.         } else {
  228.           $im=implode('', $mark);
  229.              $sel = $this->pdo->prepare("SELECT $colum from $table WHERE $im");
  230.         }
  231.  
  232.         $sel->execute($value);
  233.         $sel->setFetchMode( PDO::FETCH_OBJ );
  234.         return  $sel;
  235.     }
  236.     /**
  237.     * insert data to table
  238.     * @param  string $table table name
  239.     * @param  array $dat   associative array 'column_name'=>'val'
  240.     */
  241.     public function insert($table,$dat) {
  242.  
  243.         if( $dat !== null )
  244.         $data = array_values( $dat );
  245.         //grab keys
  246.         $cols=array_keys($dat);
  247.         $col=implode(', ', $cols);
  248.  
  249.         //grab values and change it value
  250.         $mark=array();
  251.         foreach ($data as $key) {
  252.           $keys='?';
  253.           $mark[]=$keys;
  254.         }
  255.         $im=implode(', ', $mark);
  256.         $ins = $this->pdo->prepare("INSERT INTO $table ($col) values ($im)");
  257.         $ins->execute( $data );
  258.  
  259.     }
  260.  
  261.     public function get_last_id()
  262.     {
  263.         return $this->pdo->lastInsertId();
  264.     }
  265.  
  266.     /**
  267.     * update record
  268.     * @param  string $table table name
  269.     * @param  array $dat   associative array 'col'=>'val'
  270.     * @param  string $id    primary key column name
  271.     * @param  int $val   key value
  272.     */
  273.     public function update($table,$dat,$id,$val) {
  274.         if( $dat !== null )
  275.         $data = array_values( $dat );
  276.         array_push($data,$val);
  277.         //grab keys
  278.         $cols=array_keys($dat);
  279.         $mark=array();
  280.         foreach ($cols as $col) {
  281.         $mark[]=$col."=?";
  282.         }
  283.         $im=implode(', ', $mark);
  284.         $ins = $this->pdo->prepare("UPDATE $table SET $im where $id=?");
  285.         $ins->execute( $data );
  286.  
  287.     }
  288.  
  289.     /**
  290.     * delete record
  291.     * @param  string $table table name
  292.     * @param  string $where column name for condition (commonly primay key column name)
  293.     * @param   int $id   key value
  294.     */
  295.     public function delete( $table, $where,$id ) {
  296.         $data = array( $id );
  297.         $sel = $this->pdo->prepare("Delete from $table where $where=?" );
  298.         $sel->execute( $data );
  299.     }
  300.  
  301.  
  302.     public function __destruct() {
  303.     $this->pdo = null;
  304.     }
  305.  
  306.     function get_settings($name){
  307.     if(is_file("settings.cfg")) $file = "settings.cfg";
  308.     else if (is_file("inc/settings.cfg")) $file = "inc/settings.cfg";
  309.     else return "";
  310.  
  311.     $con = file_get_contents($file);
  312.     $patt = '/'.$name.'.*=(.*)/i';
  313.     preg_match($patt, $con, $match);
  314.     return $match[1];
  315.     }
  316.  
  317.     function set_settings($name, $value){
  318.         if(is_file("settings.cfg")) $file = "settings.cfg";
  319.         else if (is_file("inc/settings.cfg")) $file = "inc/settings.cfg";
  320.         else return "";
  321.  
  322.         $con = file_get_contents($file);
  323.  
  324.         $lines = explode("\n", $con);
  325.         $settings = "";
  326.         foreach($lines as $line){
  327.             $line = trim($line);
  328.             if($line != ""){
  329.                 $setting = explode("=", $line, 2);
  330.                 if(count($setting)==2){
  331.                     $var = trim($setting[0]);
  332.                     $val = trim($setting[1]);
  333.                     if(stripos($var,$name)===0){
  334.                         $settings .= trim($name)."=".trim($value)."\n";
  335.                     }
  336.                     else $settings .= $line."\n";
  337.                 }
  338.             }
  339.         }
  340.         file_put_contents($file, $settings);
  341.     }
  342.  
  343.     function check_tb_exist()
  344.     {
  345.        return $this->fetch_custom("show tables like 'sys_modul'")->rowCount();
  346.     }
  347.  
  348.  
  349.     //write file
  350.      function buat_file($file,$isi)
  351.      {
  352.         $fp=fopen($file,'w');
  353.         if(!$fp)return 0;
  354.         fwrite($fp, $isi);
  355.         fclose($fp);return 1;
  356.  
  357.      }
  358.      //hapus directory
  359.     function deleteDirectory($dir) {
  360.         if (!file_exists($dir)) return true;
  361.         if (!is_dir($dir) || is_link($dir)) return unlink($dir);
  362.         foreach (scandir($dir) as $item) {
  363.         if ($item == '.' || $item == '..') continue;
  364.         if (!$this->deleteDirectory($dir . "/" . $item)) {
  365.         chmod($dir . "/" . $item, 0777);
  366.         if (!$this->deleteDirectory($dir . "/" . $item)) return false;
  367.         };}return rmdir($dir);
  368.     }
  369.  
  370.  
  371.  
  372.     //selected active menu
  373.     public function terpilih($nav,$group_id)
  374.     {
  375.       $pilih="";
  376.       //  $mod = $this->fetch_single_row('sys_menu','nav_act',$nav);
  377.         if ($nav!='') {
  378.              $menu = $this->fetch_custom("select * from sys_menu where url=?",array('url'=>$nav));
  379.  
  380.         foreach ($menu as $men) {
  381.  
  382.               $id_group[] = $group_id;
  383.            if ($men->parent!=0) {
  384.                $data = $this->fetch_single_row('sys_menu','id',$men->parent);
  385.  
  386.  
  387.             if ($group_id==$men->parent || $data->parent==$group_id ) {
  388.  
  389.  
  390.  
  391.              $pilih='active';
  392.             }  else {
  393.                  $pilih="";
  394.             }
  395.  
  396.            } else {
  397.                        $data = $this->fetch_single_row('sys_menu','id',$men->parent);
  398.  
  399.  
  400.             if ($group_id==$men->parent) {
  401.  
  402.  
  403.              $pilih='active';
  404.             }  else {
  405.                  $pilih="";
  406.             }
  407.            }
  408.  
  409.  
  410.  
  411.        }
  412.          }
  413.  
  414.  
  415.  
  416.         return $pilih;
  417.     }
  418.      // Menu builder function, parentId 0 is the root
  419.     function buildMenu($url,$parent, $menu)
  420.     {
  421.        $html = "";
  422.        if (isset($menu['parents'][$parent]))
  423.        {
  424.            foreach ($menu['parents'][$parent] as $itemId)
  425.            {
  426.  
  427.               if(!isset($menu['parents'][$itemId]))
  428.               {
  429.                  $html .= "<li ";
  430.                  $html .=($url==$menu['items'][$itemId]['url'])?'class="active"':'';
  431.                  $html.=">
  432.                   <a href='".base_index().$menu['items'][$itemId]['url']."'>";
  433.                  if($menu['items'][$itemId]['icon']!='')
  434.                   {
  435.                     $html.="<i class='fa ".$menu['items'][$itemId]['icon']."'></i>";
  436.                   } else {
  437.                     $html.="<i class='fa fa-circle-o'></i>";
  438.                   }
  439.                   $html.=ucwords($menu['items'][$itemId]['page_name'])."</a></li>";
  440.               }
  441.  
  442.               if(isset($menu['parents'][$itemId]))
  443.               {
  444.  
  445.  
  446.  
  447. $html .= "<li class='treeview ".$this->terpilih($url,$menu['items'][$itemId]['id']);
  448.  
  449.      $html.="'><a href='#'>";
  450.                  if($menu['items'][$itemId]['icon']!='')
  451.                   {
  452.                     $html.="<i class='fa ".$menu['items'][$itemId]['icon']."'></i>";
  453.                   } else {
  454.                     $html.="<i class='fa fa-circle-o'></i>";
  455.                   }
  456.                   $html.="<span>".ucwords($menu['items'][$itemId]['page_name'])."</span>
  457.                                    <i class='fa fa-angle-left pull-right'></i>
  458.                                </a>";
  459. $html .="<ul class='treeview-menu'>";
  460. $html .=$this->buildMenu($url,$itemId, $menu);
  461. $html .= "</ul></li>";
  462.               }
  463.            }
  464.  
  465.        }
  466.        return $html;
  467.     }
  468.  
  469.     //search function
  470.     public function getRawWhereFilterForColumns($filter, $search_columns)
  471.     {
  472.         $filter=addslashes($filter);
  473.       $search_terms = explode(' ', $filter);
  474.       $search_condition = "";
  475.  
  476.       for ($i = 0; $i < count($search_terms); $i++) {
  477.         $term = $search_terms[$i];
  478.  
  479.         for ($j = 0; $j < count($search_columns); $j++) {
  480.           if ($j == 0) $search_condition .= "(";
  481.           $search_field_name = $search_columns[$j];
  482.           $search_condition .= "$search_field_name LIKE '%" . $term . "%'";
  483.           if ($j + 1 < count($search_columns)) $search_condition .= " OR ";
  484.           if ($j + 1 == count($search_columns)) $search_condition .= ")";
  485.         }
  486.         if ($i + 1 < count($search_terms)) $search_condition .= " AND ";
  487.       }
  488.       return $search_condition;
  489.     }
  490.  
  491.       //obj to array
  492.       function convert_obj_to_array($obj)
  493.       {
  494.           if (is_object($obj)) $obj = (array)$obj;
  495.           if (is_array($obj)) {
  496.               $new = array();
  497.               foreach ($obj as $key => $val) {
  498.                   $new[$key] = $this->convert_obj_to_array($val);
  499.               }
  500.           } else {
  501.               $new = $obj;
  502.           }
  503.  
  504.           return $new;
  505.       }
  506.  
  507.  
  508.   function get_dir($dir) {
  509.       $modul_dir = explode(DIRECTORY_SEPARATOR, $dir);
  510.      array_pop($modul_dir);
  511.      array_pop($modul_dir);
  512.  
  513.      $modul_dir = implode(DIRECTORY_SEPARATOR, $modul_dir);
  514.      return $modul_dir.DIRECTORY_SEPARATOR."modul".DIRECTORY_SEPARATOR;
  515.   }
  516.  
  517.  
  518.  
  519.  
  520.     function compressImage($ext,$uploadedfile,$path,$actual_image_name,$newwidth,$tinggi=null)
  521.         {
  522.  
  523.         if($ext=="image/jpeg" || $ext=="image/jpg" )
  524.         {
  525.         $src = imagecreatefromjpeg($uploadedfile);
  526.         }
  527.         else if($ext=="image/png")
  528.         {
  529.         $src = @imagecreatefrompng($uploadedfile);
  530.         }
  531.         else if($ext=="image/gif")
  532.         {
  533.         $src = imagecreatefromgif($uploadedfile);
  534.         }
  535.         else
  536.         {
  537.         $src = imagecreatefrombmp($uploadedfile);
  538.         }
  539.  
  540.         list($width,$height)=getimagesize($uploadedfile);
  541.         if ($tinggi!=null) {
  542.             $newheight=$tinggi;
  543.         } else {
  544.             $newheight=($height/$width)*$newwidth;
  545.         }
  546.  
  547.         $tmp=imagecreatetruecolor($newwidth,$newheight);
  548.         imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
  549.         $filename = $path.$actual_image_name; //PixelSize_TimeStamp.jpg
  550.         imagejpeg($tmp,$filename,100);
  551.         imagedestroy($tmp);
  552.         return $filename;
  553.         }
  554. }
  555.  
  556. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement