Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Database{
- private static $INSTANCE = null;
- private $con,
- $HOST = 'localhost',
- $USER = 'root',
- $PASS = '',
- $DBNAME = 'dbpegawai';
- public function __construct(){
- $this->con = new mysqli($this->HOST, $this->USER, $this->PASS, $this->DBNAME);
- if(mysqli_connect_error()){
- die ('Tidak terhubung ke database');
- }
- }
- /*singleton pattern, menguju koneksi agar tidak double */
- public static function getInstance(){
- if(!isset(self::$INSTANCE)){
- self::$INSTANCE = new Database();
- }
- return self::$INSTANCE;
- }
- public function insert($table, $fields = array()){
- //mengambil column
- $column = implode(", ", array_keys($fields));
- //mengambil nilai
- $valueArrays = array();
- $i = 0;
- foreach($fields as $key=>$values) {
- if(is_int($values)){
- $valueArrays[$i] = $this->escapeInput($values);
- }else{
- $valueArrays[$i] = "'".$this->escapeInput($values)."'";
- }
- $i++;
- }
- $values = implode(", ", $valueArrays);
- $query = "INSERT INTO $table($column) Values($values)";
- return $this->run_query($query, 'Insert data gagal');
- }
- public function run_query($query, $msg) {
- if($this->con->query($query))
- return true;
- else
- die($msg);
- }
- public function escapeInput($name) {
- return $this->con->real_escape_string($name);
- }
- public function getInfo($table, $column='', $value='') {
- if(!is_int($value)){
- $value = "'".$value."'";
- }
- if($column != '') {
- $query = "SELECT * FROM $table WHERE $column = $value";
- $result = $this->con->query($query);
- while ($row = $result->fetch_assoc()){
- return $row;
- }
- }else{
- $query = "SELECT * FROM $table";
- $result = $this->con->query($query);
- while($row = $result->fetch_assoc()) {
- $result[] = $row;
- }
- return $result;
- }
- }
- public function update($table, $field, $id) {
- //mengambil nilai
- $valueArrays = array();
- $i = 0;
- foreach($field as $key=>$values) {
- //update table set kunci1=nilai, kunci2=nilai...
- if(is_int($values)){
- $valueArrays[$i]= $key ."=". $this->escapeInput($values);
- }else{
- $valueArrays[$i]= $key ."='". $this->escapeInput($values)."'";
- }
- $i++;
- }
- $values = implode(", ", $valueArrays);
- $query = "UPDATE $table SET $values WHERE id = $id";
- // die($quiery);
- return $this->run_query($query, 'ada masalah update');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement