vic4884
9/22/2019 - 12:30 PM

DataBase class

DataBase class

<?php

class Database
{
	public $is_connect;
	protected $db;


	//connect
	public function __construct($username = 'root', $passsword = 'root', $host = 'localhost', $dbname = 'dbname', $options = [])
	{
		$this->is_connect = true;
		try {
			$this->db = new PDO("mysql:host={$host}; dbname={$dbname}; charset=utf8", $username, $passsword, $options);
			$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
		} catch (PDOException $e) {
			throw new Exception($e->getMessage());
		}
	}

	//disconnect
	public function disconnect()
	{
		$this->db = null;
		$this->is_connect = false;
	}

	//get row
	public function get_row($query, $params = [])
	{
		try {
			$stmt = $this->db->prepare($query);
			$stmt->execute($params);
			return $stmt->fetch();
		} catch (PDOException $e) {
			throw new Exception($e->getMessage());
		}
	}

	//get rows
	public function get_rows($query, $params = [])
	{
		try {
			$stmt = $this->db->prepare($query);
			$stmt->execute($params);
			return $stmt->fetchAll();
		} catch (PDOException $e) {
			throw new Exception($e->getMessage());
		}
	}


	//insert row
	public function insert_row($query, $params = [])
	{
		try {
			$stmt = $this->db->prepare($query);
			$stmt->execute($params);
			return true;
		} catch (PDOException $e) {
			throw new Exception($e->getMessage());
		}
	}


	//update row
	public function update_row($query, $params = [])
	{
		$this->insert_row($query, $params);
	}


	//delete row
	public function delete_row($query, $params = [])
	{
		$this->insert_row($query, $params);
	}
}

/*
  $db = new Database();
  $query =  "SELECT * FROM table WHERE id = ?";
  $get_row = $db->get_row($query, ["1"]); $params = ["1"]
  print_r($get_row);
  
  
  $insertRow = $db->insertRow("INSERT INTO users(username, pass, email) values (?, ?, ?)" , ['noname', '123', 'email@mail.com']);
  
  $update = $db->updateRow('UPDATE users SET username = ?, password = ? WHERE id = ?', ['name', 'password123', 2]);
  
  
  
*/