Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Database extends mysqli
- {
- private $host;
- private $user;
- private $pass;
- private $dbName;
- private $connect;
- private $result;
- public function __construct($host, $user, $pass, $dbname)
- {
- $this->host = $host;
- $this->user = $user;
- $this->pass = $pass;
- $this->dbName = $dbname;
- $this->connect();
- }
- public function connect()
- {
- $this->connect = mysqli_connect($this->host, $this->user, $this->pass, $this->dbName) or
- die("Connection to Database failed.");
- }
- public function query($sql)
- {
- $result = $this->connect->query($sql);
- return $result;
- }
- public function createTable()
- {
- $sql = "CREATE TABLE products (id INT NOT NULL AUTO_INCREMENT, name TEXT,
- price NUMERIC(15,2), description TEXT, PRIMARY KEY (id))";
- return $this->connect->query($sql);
- }
- public function insert($tableName, $data)
- {
- $sql = "INSERT INTO {$tableName}";
- $keys = "";
- $values = "";
- foreach ($data as $key => $value)
- {
- $keys .= $key . ",";
- $values .= "'".$value . "',";
- }
- $sql .= "(" . substr($keys, 0, -1). ") VALUES(".substr($values,0,-1).")";
- return $this->connect->query($sql);
- }
- public function update($tableName, $data, $id)
- {
- $sql = "UPDATE {$tableName} SET";
- $values = "";
- foreach ($data as $key => $value)
- {
- $values .= $key. "=" . "" . $value . ",";
- }
- $sql .= substr($values, 0, -2). " WHERE id = {$id}";
- return $this->connect->query($sql);
- }
- public function resetTable($tableName)
- {
- $sql = "truncate $tableName";
- return $this->connect->query($sql);
- }
- public function delete($tableName, $id)
- {
- $sql = "DELETE FROM {$tableName} WHERE id = {$id}";
- return $this->connect->query($sql);
- }
- public function getDataFromTable($tableName)
- {
- $sql = "SELECT * FROM $tableName";
- $result = $this->connect->query($sql);
- $products = array();
- $count = 1;
- if (mysqli_num_rows($result) > 0) {
- while ($row = mysqli_fetch_assoc($result)) {
- $product = array(
- 'name' => $row['name'],
- 'price' => $row['price'],
- 'description' => $row['description']
- );
- array_push($products, $product);
- $count++;
- }
- }
- return $products;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement