Untitled

 avatar
unknown
php
3 years ago
2.1 kB
4
Indexable
<?php

    class Book {
        private $id;
        private $title;
        private $author;
        private $year;
        
        public function __construct($id, $title, $author, $year) {
            $this->id = $id;
            $this->$title = $title;
            $this->author = $author;
            $this->year = $year;
        }
        
        public function __toString() {
            return $this->id ." " .$this->title ." " .$this->author ." " .$this->year ."<br>";
        }
    }
    
    class Db {
        const host = "localhost";
        const user = "root";
        const pass = "";
        const db_name= "book";
        private $dbh;
        
        
        public function __construct() {
            $this->dbh = new mysqli(self::host, self::user, self::pass, self::db_name);
            
            if (mysqli_connect_errno()) {
                die("Connection to database failed!");
            }
        }
        
        public function __destruct() {
            $this->dbh->close();
        }
        
        public function getAllBooks() {
            try {
                $query = "SELECT * FROM knjiga";
                $res = $this->dbh->query($query);
                
                $books = [];
                while ($row = $res->fetch_array()) {
                    $book = new Book($row[0], $row[1], $row[2], $row[3]);
                    $books[] = $book;
                }
                return $books;
                
            } catch (Exception $ex) {
                die($ex->getMessage());
            }
        }
    }

    public function getAllBooks() {
        try {
            $query = "SELECT * FROM knjiga";
            $res = $this->dbh->query($query);
            $rows = $res->fetch_all(MYSQLI_ASSOC);

            $books = [];
            foreach ($rows as $row) {
                $book = new Book($row['id'], $row['naslov'], $row['autor'], $row['godina']);
                $books[] = $book;
            }
            return $books;

        } catch (Exception $ex) {
            die($ex->getMessage());
        }
    }

?>
Editor is loading...