diff --git a/API Cursos.PNG b/API Cursos.PNG new file mode 100644 index 000000000..aab421da4 Binary files /dev/null and b/API Cursos.PNG differ diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 7c160f4e9..000000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 celsolisboa - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md index 86d70e367..b81b9e719 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,79 @@ -# Desafio Celso Lisboa para FullStack - -### Cenário - -**Como** Coordenador Acadêmico de uma Instituição de Ensino -**Eu preciso** realizar a gestão dos cursos oferecidos pela Instituição, com seus respectivos professores, salas e horários -**Para** que o setor de Marketing possa vender os cursos online. - -### Segue instruções para realizar o desafio - -1. Faça um fork deste repositório. -2. Baseado no cenário acima, modele e crie o esquema do banco de dados para armazenar as informações normalizadas. - * Comite a imagem em jpg ou png do DER e o script do DDL. -3. Desenvolva uma API REST para realizar as operações necessárias com o banco de dados criado. -4. Baseado nas imagens `wireframe/1-login-mobile.png` e `wireframe/2-login-desktop.png`, crie a tela de login da aplicação. - * Considere apenas uma validação simples por e-mail e senha. - * Não existe a necessidade de CRUD de usuário, recuperação de senha ou outra operação mais complexa. -5. Baseado nas imagens `wireframe/3-cursos-mobile.png` e `wireframe/4-cursos-desktop.png`, crie a tela de visualização e deleção de cursos. - * Deve conter as informações de horário, professor e sala. -6. Baseado nas imagens `wireframe/5-detalhe-mobile.png` e `wireframe/6-detalhe-desktop.png`, crie a tela de criação e alteração de cursos. - * Os campos de professor e sala deverão ser um multi-select. - * Não existe a necessidade de CRUD de professor e sala. -7. Realizar um Pull Request para este repositório, com instruções necessárias para instalação e instânciação dos sistemas. - -### O que será avaliado - -1. Fidelidade às instruções e ao cenário. -2. Clean Code e boas práticas. -3. Boas práticas de versionamento. +API Curso + +#Introdução
+ +Esta API executa um CRUD de informações sobre curso. +Exibindo no formato JSON: curso, Professor, Sala, Horário de início e horário de fim. +Este projeto é simples e básico. +O intuito deste é mostrar de forma fácil como consumir dados utilizando padrão Rest. + +#Instalação
+ +1- Utilize o arquivo apiCursos.sql, para a criação da base de dados.
+2- Modifique o arquivo api/config/config.php, com as informações para acessar o banco de dados MYSQL.
+3- Crie um diretório no servidor web com o nome "curso" e baixe e descompacte o conteúdo deste repositório.
+4- Por padrão usuario: admin@admin.com e senha: 123456.
+ +#Sobre
+ +Neste projeto foi utilizado o AJAX para comunicação da interface com a API.
+Não foi utilizado validações de sala, horário, autenticação dentro outras deixando o projeto o mais básico possível.
+ +#Autenticação
+ +Não existe autenticação com a API. O login é básico utilizando apenas autenticação de usuario e senha.
+ +#Codigos de Erro
+ +Codigos de status e erros.
+ +create
+201 - Cadastrado com sucesso.
+503 - Serviço indisponível, problemas para criar o curso.
+400 - Dados incompetos.
+ +Delete
+200 - O curso foi deletado com sucesso.
+503 - Serviço indisponível, problemas para deletar o curso
+ +Loging
+200 - Logado com sucesso.
+503 - Erro ao logar.
+ +read_one
+200 - Curso localizado com sucesso.
+503 - Curso não existe.
+ +read_paging
+200 - Sucesso na paginação.
+404 - Nenhum curso encontrado.
+ +read
+200 - listar cursos com sucesso.
+404 - Nenhum curso encontrado.
+ +search
+200 - curso localizado com sucesso.
+404 - Nenhum curso encontrado.
+ +update
+200 - Curso atualizado com sucesso.
+503 - Serviço indisponível, problemas para atualizar o curso.
+ +---------------------------------------------------- +#Rotas
+ +Lista os cursos
+POST curso/api/curso/read.php
+ +Lista o curso selecionado pelo idcurso
+GET curso/api/curso/read_one.php?idcurso=
+ +Deleta o curso selecionado pelo idcurso
+GET curso/api/curso/delete.php?idcurso=
+ +Cadastra curso
+POST curso/api/curso/create.php
+ +Atualiza dados de um curso selecionado pelo idcurso
+GET curso/api/curso/update.php?idcurso=
diff --git a/api/config/config.php b/api/config/config.php new file mode 100644 index 000000000..b0b3a009f --- /dev/null +++ b/api/config/config.php @@ -0,0 +1,8 @@ + + diff --git a/api/config/core.php b/api/config/core.php new file mode 100644 index 000000000..fc4dc97a8 --- /dev/null +++ b/api/config/core.php @@ -0,0 +1,17 @@ + \ No newline at end of file diff --git a/api/config/database.php b/api/config/database.php new file mode 100644 index 000000000..859d4349e --- /dev/null +++ b/api/config/database.php @@ -0,0 +1,31 @@ +setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + self::$instance->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); + } catch (PDOException $e) { + echo $e->getMessage(); + } + + } + + return self::$instance; + } + + public static function prepare($sql){ + return self::getConnection()->prepare($sql); + } + +} +?> \ No newline at end of file diff --git a/api/curso/create.php b/api/curso/create.php new file mode 100644 index 000000000..8d2636d44 --- /dev/null +++ b/api/curso/create.php @@ -0,0 +1,71 @@ +getConnection(); + +$curso = new Curso($db); + +// get posted data + +$data = json_decode(file_get_contents("php://input")); + +// make sure data is not empty +if( + !empty($data->curso) && + !empty($data->idprofessor) && + !empty($data->idsala) && + !empty($data->inicio) && + !empty($data->fim) +){ + + // set curso property values + $curso->curso = $data->curso; + $curso->idprofessor = $data->idprofessor; + $curso->idsala = $data->idsala; + $curso->inicio = $data->inicio; + $curso->fim = $data->fim; + + // create the curso + if($curso->create()){ + + // set response code - 201 created + http_response_code(201); + + // tell the user + echo json_encode(array("message" => "Curso de ".$curso->curso." criado com sucesso.")); + } + + // if unable to create the product, tell the user + else{ + + // set response code - 503 service unavailable + http_response_code(503); + + // tell the user + echo json_encode(array("message" => "Problemas para criar o Curso.")); + } +} + +// tell the user data is incomplete +else{ + + // set response code - 400 bad request + http_response_code(400); + + // tell the user + echo json_encode(array("message" => "Problemas para criar o Curso. Dados incompletos.")); + +} +?> \ No newline at end of file diff --git a/api/curso/delete.php b/api/curso/delete.php new file mode 100644 index 000000000..09fed39a1 --- /dev/null +++ b/api/curso/delete.php @@ -0,0 +1,46 @@ +getConnection(); + +// prepare curso object +$curso = new Curso($db); + +// get curso id +//$data = json_decode(file_get_contents("php://input")); + +// set curso id to be deleted +$curso->idcurso = isset($_GET['idcurso']) ? $_GET['idcurso'] : die(); +//$curso->idcurso = $data->idcurso; + +// delete the curso +if($curso->delete()){ + + // set response code - 200 ok + http_response_code(200); + + // tell the user + echo json_encode(array("message" => "O Curso foi deletado.")); +} + +// if unable to delete the curso +else{ + + // set response code - 503 service unavailable + http_response_code(503); + + // tell the user + echo json_encode(array("message" => "Problemas para deletar o Curso.")); +} +?> \ No newline at end of file diff --git a/api/curso/loging.php b/api/curso/loging.php new file mode 100644 index 000000000..d67f1d3f7 --- /dev/null +++ b/api/curso/loging.php @@ -0,0 +1,51 @@ +getConnection(); + +// prepare curso object +$curso = new Curso($db); + +$data = json_decode(file_get_contents("php://input")); + +// set ID property of record to read +$curso->usuario = $data->usuario; +$curso->senha = $data->senha; + +// read the details of curso to be edited +$curso->login(); + + if($curso->usuario!=null){ + // create array + $curso_arr = array( + "usuario" => $curso->usuario + ); + + // set response code - 200 OK + http_response_code(200); + + // make it json format + session_start(); + $_SESSION['usuario'] = $curso->usuario; + $_SESSION['id'] = session_id(); + echo json_encode(array("message" => "Logado com sucesso.")); + } + + else{ + // set response code - + http_response_code(503); + + echo json_encode(array("message" => "Erro ao logar.")); + } +?> \ No newline at end of file diff --git a/api/curso/read.php b/api/curso/read.php new file mode 100644 index 000000000..6aeb88064 --- /dev/null +++ b/api/curso/read.php @@ -0,0 +1,67 @@ +getConnection(); + +// initialize object +$curso = new Curso($db); + +// read products will be here +// query products +$stmt = $curso->read(); +$num = $stmt->rowCount(); + +// check if more than 0 record found +if($num>0){ + + // cursos array + $cursos_arr=array(); + $cursos_arr["records"]=array(); + + // retrieve our table contents + // fetch() is faster than fetchAll() + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ + // extract row + // this will make $row['name'] to + // just $name only + extract($row); + + $curso_item=array( + "idcurso" => $idcurso, + "curso" => html_entity_decode($curso), + "idprofessor" => $idprofessor, + "professor" => $professor, + "idsala" => $idsala, + "sala" => $sala, + "inicio" => $inicio, + "fim" => $fim + ); + + array_push($cursos_arr["records"], $curso_item); + } + + // set response code - 200 OK + http_response_code(200); + + // show cursos data in json format + echo json_encode($cursos_arr); +}else{ + + // set response code - 404 Not found + http_response_code(404); + + // tell the user no products found + echo json_encode( + array("message" => "Nenhum Curso encontrado.") + ); +} \ No newline at end of file diff --git a/api/curso/read_one.php b/api/curso/read_one.php new file mode 100644 index 000000000..94a14a8a9 --- /dev/null +++ b/api/curso/read_one.php @@ -0,0 +1,54 @@ +getConnection(); + +// prepare curso object +$curso = new Curso($db); + +// set ID property of record to read +$curso->idcurso = isset($_GET['idcurso']) ? $_GET['idcurso'] : die(); + +// read the details of curso to be edited +$curso->readOne(); + +if($curso->curso!=null){ + // create array + $curso_arr = array( + "idcurso" => $curso->idcurso, + "curso" => $curso->curso, + "idprofessor" => $curso->idprofessor, + "professor" => $curso->professor, + "idsala" => $curso->idsala, + "sala" => $curso->sala, + "inicio" => $curso->inicio, + "fim" => $curso->fim + + ); + + // set response code - 200 OK + http_response_code(200); + + // make it json format + echo json_encode($curso_arr); +} + +else{ + // set response code - 404 Not found + http_response_code(404); + + // tell the curso does not exist + echo json_encode(array("message" => "Este Curso não existe.")); +} +?> \ No newline at end of file diff --git a/api/curso/read_paging.php b/api/curso/read_paging.php new file mode 100644 index 000000000..2df4693f2 --- /dev/null +++ b/api/curso/read_paging.php @@ -0,0 +1,80 @@ +getConnection(); + +// initialize object +$curso = new Curso($db); + +// query cursos +$stmt = $curso->readPaging($from_record_num, $records_per_page); +$num = $stmt->rowCount(); + +// check if more than 0 record found +if($num>0){ + + // cursos array + $cursos_arr=array(); + $cursos_arr["records"]=array(); + $cursos_arr["paging"]=array(); + + // retrieve our table contents + // fetch() is faster than fetchAll() + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ + // extract row + // this will make $row['curso'] to + // just $curso only + extract($row); + + $curso_item=array( + "idcurso" => $idcurso, + "curso" => $curso, + "professor" => $professor, + "sala" => $sala, + "inicio" => $inicio, + "fim" => $fim + ); + + array_push($cursos_arr["records"], $curso_item); + } + + + // include paging + + $total_rows= '$curso->total()'; + $page_url="{$home_url}curso/read_paging.php?"; + $paging=$utilities->getPaging($page, $total_rows, $records_per_page, $page_url); + $cursos_arr["paging"]=$paging; + + // set response code - 200 OK + http_response_code(200); + + // make it json format + echo json_encode($cursos_arr); +} + +else{ + + // set response code - 404 Not found + http_response_code(404); + + // tell the user cursos does not exist + echo json_encode( + array("message" => "Nenhum curso encontrado.") + ); +} +?> \ No newline at end of file diff --git a/api/curso/search.php b/api/curso/search.php new file mode 100644 index 000000000..8fabc773b --- /dev/null +++ b/api/curso/search.php @@ -0,0 +1,69 @@ +getConnection(); + +// initialize object +$curso = new Curso($db); + +// get keywords +$keywords=isset($_GET["s"]) ? $_GET["s"] : ""; + +// query cursos +$stmt = $curso->search($keywords); +$num = $stmt->rowCount(); + +// check if more than 0 record found +if($num>0){ + + // cursos array + $cursos_arr=array(); + $cursos_arr["records"]=array(); + + // retrieve our table contents + // fetch() is faster than fetchAll() + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ + // extract row + // this will make $row['curso'] to + // just $curso only + extract($row); + + $curso_item=array( + "idcurso" => $idcurso, + "curso" => html_entity_decode($curso), + "professor" => $professor, + "sala" => $sala, + "inicio" => $inicio, + "fim" => $fim + ); + + array_push($cursos_arr["records"], $curso_item); + } + + // set response code - 200 OK + http_response_code(200); + + // show cursos data + echo json_encode($cursos_arr); +} + +else{ + // set response code - 404 Not found + http_response_code(404); + + // tell the user no cursos found + echo json_encode( + array("message" => "Nenhum registro encontrado.") + ); +} +?> diff --git a/api/curso/update.php b/api/curso/update.php new file mode 100644 index 000000000..88b7a8390 --- /dev/null +++ b/api/curso/update.php @@ -0,0 +1,52 @@ +getConnection(); + +// prepare curso object +$curso = new Curso($db); + +// get id of curso to be edited +$data = json_decode(file_get_contents("php://input")); + +// set ID property of curso to be edited +$curso->idcurso = $data->idcurso; + +// set curso property values +$curso->curso = $data->curso; +$curso->idprofessor = $data->idprofessor; +$curso->idsala = $data->idsala; +$curso->inicio = $data->inicio; +$curso->fim = $data->fim; + +// update the curso +if($curso->update()){ + + // set response code - 200 ok + http_response_code(200); + + // tell the user + echo json_encode(array("message" => "O Curso foi Atualizado.")); +} + +// if unable to update the curso, tell the user +else{ + + // set response code - 503 service unavailable + http_response_code(503); + + // tell the user + echo json_encode(array("message" => "Problemas para atualizar o curso.")); +} +?> diff --git a/api/objetos/curso.php b/api/objetos/curso.php new file mode 100644 index 000000000..a28ed200d --- /dev/null +++ b/api/objetos/curso.php @@ -0,0 +1,291 @@ +conn = $db; + } + + + public function login(){ + + // query to read single record + $query ="SELECT + usuario, senha + FROM + usuarios + WHERE + usuario = ? AND + senha = ?"; + + // prepare query statement + $stmt = $this->conn->prepare( $query ); + + // bind id of login to be updated + $stmt->bindParam(1, $this->usuario); + $stmt->bindParam(2, $this->senha); + + // execute query + $stmt->execute(); + + // get retrieved row + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + // set values to object properties + $this->usuario = $row['usuario']; + + } + + // read cursos + function read(){ + + // select all query + $query = "SELECT + c.idcurso, c.curso,c.idprofessor, p.professor,c.idsala, s.sala, c.inicio, c.fim + FROM + cursos c, professores p, salas s + WHERE + c.idprofessor = p.idprofessor and + c.idsala = s.idsala + ORDER BY + c.idcurso"; + + // prepare query statement + $stmt = $this->conn->prepare($query); + + // execute query + $stmt->execute(); + + return $stmt; + } + + // create curso + public function create(){ + + // query to insert record + $query = "INSERT INTO + cursos (curso, idprofessor, idsala, inicio, fim) + VALUES (:curso, :idprofessor, :idsala, :inicio, :fim)"; + + + // prepare query + $stmt = $this->conn->prepare($query); + + // sanitize + $this->curso=htmlspecialchars(strip_tags($this->curso)); + $this->idprofessor=htmlspecialchars(strip_tags($this->idprofessor)); + $this->idsala=htmlspecialchars(strip_tags($this->idsala)); + $this->inicio=htmlspecialchars(strip_tags($this->inicio)); + $this->fim=htmlspecialchars(strip_tags($this->fim)); + + // bind values + $stmt->bindParam(":curso", $this->curso); + $stmt->bindParam(":idprofessor", $this->idprofessor); + $stmt->bindParam(":idsala", $this->idsala); + $stmt->bindParam(":inicio", $this->inicio); + $stmt->bindParam(":fim", $this->fim); + + // execute query + if($stmt->execute()){ + return true; + } + + return false; + + } + + // used when filling up the update product form + public function readOne(){ + + // query to read single record + $query ="SELECT + c.idcurso, c.curso, c.idprofessor, p.professor, c.idsala, s.sala, c.inicio, c.fim + FROM + cursos c, professores p, salas s + WHERE + c.idprofessor = p.idprofessor AND + c.idsala = s.idsala AND + c.idcurso = ? + LIMIT + 0,1"; + + // prepare query statement + $stmt = $this->conn->prepare( $query ); + + // bind id of product to be updated + $stmt->bindParam(1, $this->idcurso); + + // execute query + $stmt->execute(); + + // get retrieved row + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + // set values to object properties + $this->curso = $row['curso']; + $this->idprofessor = $row['idprofessor']; + $this->professor = $row['professor']; + $this->idsala = $row['idsala']; + $this->sala = $row['sala']; + $this->inicio = $row['inicio']; + $this->fim = $row['fim']; + } + + // update the curso + public function update(){ + + // update query + $query = "UPDATE + cursos + SET + curso = :curso, + idprofessor = :idprofessor, + idsala = :idsala, + inicio = :inicio, + fim = :fim + WHERE + idcurso = :idcurso"; + + // prepare query statement + $stmt = $this->conn->prepare($query); + + // sanitize + $this->curso=htmlspecialchars(strip_tags($this->curso)); + $this->idprofessor=htmlspecialchars(strip_tags($this->idprofessor)); + $this->idsala=htmlspecialchars(strip_tags($this->idsala)); + $this->inicio=htmlspecialchars(strip_tags($this->inicio)); + $this->fim=htmlspecialchars(strip_tags($this->fim)); + $this->idcurso=htmlspecialchars(strip_tags($this->idcurso)); + + // bind new values + $stmt->bindParam(':curso', $this->curso); + $stmt->bindParam(':idprofessor', $this->idprofessor); + $stmt->bindParam(':idsala', $this->idsala); + $stmt->bindParam(':inicio', $this->inicio); + $stmt->bindParam(':fim', $this->fim); + $stmt->bindParam(':idcurso', $this->idcurso); + + // execute the query + if($stmt->execute()){ + return true; + } + + return false; + } + + // delete the curso + public function delete(){ + + // delete query + $query = "DELETE FROM cursos WHERE idcurso = ?"; + + // prepare query + $stmt = $this->conn->prepare($query); + + // sanitize + $this->idcurso=htmlspecialchars(strip_tags($this->idcurso)); + + // bind id of record to delete + $stmt->bindParam(1, $this->idcurso); + + // execute query + if($stmt->execute()){ + return true; + } + + return false; + + } + + // search products + public function search($keywords){ + + // select all query + $query = "SELECT + c.idcurso, c.curso, p.professor, s.sala, c.inicio, c.fim + FROM + cursos c + INNER JOIN + professores p ON c.idprofessor = p.idprofessor + INNER JOIN + salas s ON c.idsala = s.idsala + WHERE + c.curso LIKE ? OR p.professor LIKE ? OR s.sala LIKE ? + ORDER BY + c.curso DESC"; + + // prepare query statement + $stmt = $this->conn->prepare($query); + + // sanitize + $keywords=htmlspecialchars(strip_tags($keywords)); + $keywords = "%{$keywords}%"; + + // bind + $stmt->bindParam(1, $keywords); + $stmt->bindParam(2, $keywords); + $stmt->bindParam(3, $keywords); + + // execute query + $stmt->execute(); + + return $stmt; + } + + // read products with pagination + public function readPaging($from_record_num, $records_per_page){ + + // select query + $query = "SELECT + c.idcurso, c.curso, p.professor, s.sala, c.inicio, c.fim + FROM + cursos c, professores p, salas s + WHERE + c.idprofessor = p.idprofessor and + c.idsala = s.idsala + ORDER BY + c.idcurso DESC + LIMIT ?, ?"; + + // prepare query statement + $stmt = $this->conn->prepare( $query ); + + // bind variable values + $stmt->bindParam(1, $from_record_num, PDO::PARAM_INT); + $stmt->bindParam(2, $records_per_page, PDO::PARAM_INT); + + // execute query + $stmt->execute(); + + // return values from database + return $stmt; + } + + // used for paging products + public function total(){ + $query = "SELECT COUNT(*) as total FROM cursos"; + + $stmt = $this->conn->prepare( $query ); + $stmt->execute(); + $row = $stmt->fetchAll(PDO::FETCH_ASSOC); + + return $row['total']; + } +} \ No newline at end of file diff --git a/api/objetos/professor.php b/api/objetos/professor.php new file mode 100644 index 000000000..029a3051b --- /dev/null +++ b/api/objetos/professor.php @@ -0,0 +1,213 @@ +conn = $db; + } + + // read professores + function read(){ + + // select all query + $query = "SELECT + idprofessor, professor + FROM + professores + ORDER BY + idprofessor"; + + // prepare query statement + $stmt = $this->conn->prepare($query); + + // execute query + $stmt->execute(); + + return $stmt; + } + + // create professor + public function create(){ + + // query to insert record + $query = "INSERT INTO + professores + SET + professor=:professor"; + + // prepare query + $stmt = $this->conn->prepare($query); + + // sanitize + $this->professor=htmlspecialchars(strip_tags($this->professor)); + + // bind values + $stmt->bindParam(":professor", $this->professor); + + // execute query + if($stmt->execute()){ + return true; + } + + return false; + + } + + // used when filling up the update product form + public function readOne(){ + + // query to read single record + $query ="SELECT + idprofessor, professor + FROM + professores + WHERE + idprofessor = ? + LIMIT + 0,1"; + + // prepare query statement + $stmt = $this->conn->prepare( $query ); + + // bind id of product to be updated + $stmt->bindParam(1, $this->idprofessor); + + // execute query + $stmt->execute(); + + // get retrieved row + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + // set values to object properties + $this->idprofessor = $row['idprofessor']; + $this->professor = $row['professor']; + } + + // update the professor + public function update(){ + + // update query + $query = "UPDATE + professores + SET + professor = :professor, + WHERE + idprofessor = :idprofessor"; + + // prepare query statement + $stmt = $this->conn->prepare($query); + + // sanitize + $this->professor=htmlspecialchars(strip_tags($this->professor)); + $this->idprofessor=htmlspecialchars(strip_tags($this->idprofessor)); + // bind new values + $stmt->bindParam(':professor', $this->professor); + $stmt->bindParam(':idprofessor', $this->idprofessor); + + // execute the query + if($stmt->execute()){ + return true; + } + + return false; + } + + // delete the professor + public function delete(){ + + // delete query + $query = "DELETE FROM professores WHERE idprofessor = ?"; + + // prepare query + $stmt = $this->conn->prepare($query); + + // sanitize + $this->idprofessor=htmlspecialchars(strip_tags($this->idprofessor)); + + // bind id of record to delete + $stmt->bindParam(1, $this->idprofessor); + + // execute query + if($stmt->execute()){ + return true; + } + + return false; + + } + + // search products + public function search($keywords){ + + // select all query + $query = "SELECT + idprofessor, professor + FROM + professores + WHERE + professor LIKE ? + ORDER BY + professor DESC"; + + // prepare query statement + $stmt = $this->conn->prepare($query); + + // sanitize + $keywords=htmlspecialchars(strip_tags($keywords)); + $keywords = "%{$keywords}%"; + + // bind + $stmt->bindParam(1, $keywords); + + // execute query + $stmt->execute(); + + return $stmt; + } + + // read professores with pagination + public function readPaging($from_record_num, $records_per_page){ + + // select query + $query = "SELECT + idprofessor, professor + FROM + professores + ORDER BY + professor DESC + LIMIT ?, ?"; + + // prepare query statement + $stmt = $this->conn->prepare( $query ); + + // bind variable values + $stmt->bindParam(1, $from_record_num, PDO::PARAM_INT); + $stmt->bindParam(2, $records_per_page, PDO::PARAM_INT); + + // execute query + $stmt->execute(); + + // return values from database + return $stmt; + } + + // used for paging professores + public function total(){ + $query = "SELECT COUNT(*) as total FROM professores"; + + $stmt = $this->conn->prepare( $query ); + $stmt->execute(); + $row = $stmt->fetchAll(PDO::FETCH_ASSOC); + + return $row['total']; + } +} \ No newline at end of file diff --git a/api/objetos/sala.php b/api/objetos/sala.php new file mode 100644 index 000000000..604679d90 --- /dev/null +++ b/api/objetos/sala.php @@ -0,0 +1,213 @@ +conn = $db; + } + + // read salaes + function read(){ + + // select all query + $query = "SELECT + idsala, sala + FROM + salas + ORDER BY + idsala"; + + // prepare query statement + $stmt = $this->conn->prepare($query); + + // execute query + $stmt->execute(); + + return $stmt; + } + + // create sala + public function create(){ + + // query to insert record + $query = "INSERT INTO + salas + SET + sala=:sala"; + + // prepare query + $stmt = $this->conn->prepare($query); + + // sanitize + $this->sala=htmlspecialchars(strip_tags($this->sala)); + + // bind values + $stmt->bindParam(":sala", $this->sala); + + // execute query + if($stmt->execute()){ + return true; + } + + return false; + + } + + // used when filling up the update product form + public function readOne(){ + + // query to read single record + $query ="SELECT + idsala, sala + FROM + salas + WHERE + idsala = ? + LIMIT + 0,1"; + + // prepare query statement + $stmt = $this->conn->prepare( $query ); + + // bind id of product to be updated + $stmt->bindParam(1, $this->idsala); + + // execute query + $stmt->execute(); + + // get retrieved row + $row = $stmt->fetch(PDO::FETCH_ASSOC); + + // set values to object properties + $this->idsala = $row['idsala']; + $this->sala = $row['sala']; + } + + // update the sala + public function update(){ + + // update query + $query = "UPDATE + salas + SET + sala = :sala, + WHERE + idsala = :idsala"; + + // prepare query statement + $stmt = $this->conn->prepare($query); + + // sanitize + $this->sala=htmlspecialchars(strip_tags($this->sala)); + $this->idsala=htmlspecialchars(strip_tags($this->idsala)); + // bind new values + $stmt->bindParam(':sala', $this->sala); + $stmt->bindParam(':idsala', $this->idsala); + + // execute the query + if($stmt->execute()){ + return true; + } + + return false; + } + + // delete the sala + public function delete(){ + + // delete query + $query = "DELETE FROM salas WHERE idsala = ?"; + + // prepare query + $stmt = $this->conn->prepare($query); + + // sanitize + $this->idsala=htmlspecialchars(strip_tags($this->idsala)); + + // bind id of record to delete + $stmt->bindParam(1, $this->idsala); + + // execute query + if($stmt->execute()){ + return true; + } + + return false; + + } + + // search products + public function search($keywords){ + + // select all query + $query = "SELECT + idsala, sala + FROM + salas + WHERE + sala LIKE ? + ORDER BY + sala DESC"; + + // prepare query statement + $stmt = $this->conn->prepare($query); + + // sanitize + $keywords=htmlspecialchars(strip_tags($keywords)); + $keywords = "%{$keywords}%"; + + // bind + $stmt->bindParam(1, $keywords); + + // execute query + $stmt->execute(); + + return $stmt; + } + + // read salaes with pagination + public function readPaging($from_record_num, $records_per_page){ + + // select query + $query = "SELECT + idsala, sala + FROM + salas + ORDER BY + sala DESC + LIMIT ?, ?"; + + // prepare query statement + $stmt = $this->conn->prepare( $query ); + + // bind variable values + $stmt->bindParam(1, $from_record_num, PDO::PARAM_INT); + $stmt->bindParam(2, $records_per_page, PDO::PARAM_INT); + + // execute query + $stmt->execute(); + + // return values from database + return $stmt; + } + + // used for paging salas + public function total(){ + $query = "SELECT COUNT(*) as total FROM salas"; + + $stmt = $this->conn->prepare( $query ); + $stmt->execute(); + $row = $stmt->fetchAll(PDO::FETCH_ASSOC); + + return $row['total']; + } +} \ No newline at end of file diff --git a/api/professor/read.php b/api/professor/read.php new file mode 100644 index 000000000..1487dd316 --- /dev/null +++ b/api/professor/read.php @@ -0,0 +1,61 @@ +getConnection(); + +// initialize object +$prof = new Professor($db); + +// read professores will be here +// query professores +$stmt = $prof->read(); +$num = $stmt->rowCount(); + +// check if more than 0 record found +if($num>0){ + + // profs array + $profs_arr=array(); + $profs_arr["records"]=array(); + + // retrieve our table contents + // fetch() is faster than fetchAll() + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ + // extract row + // this will make $row['name'] to + // just $name only + extract($row); + + $prof_item=array( + "idprofessor" => $idprofessor, + "professor" => html_entity_decode($professor), + ); + + array_push($profs_arr["records"], $prof_item); + } + + // set response code - 200 OK + http_response_code(200); + + // show profs data in json format + echo json_encode($profs_arr); +}else{ + + // set response code - 404 Not found + http_response_code(404); + + // tell the user no products found + echo json_encode( + array("message" => "Nenhum Professor encontrado.") + ); +} \ No newline at end of file diff --git a/api/sala/read.php b/api/sala/read.php new file mode 100644 index 000000000..45cbb482d --- /dev/null +++ b/api/sala/read.php @@ -0,0 +1,61 @@ +getConnection(); + +// initialize object +$sala = new Sala($db); + +// read products will be here +// query products +$stmt = $sala->read(); +$num = $stmt->rowCount(); + +// check if more than 0 record found +if($num>0){ + + // salas array + $salas_arr=array(); + $salas_arr["records"]=array(); + + // retrieve our table contents + // fetch() is faster than fetchAll() + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ + // extract row + // this will make $row['name'] to + // just $name only + extract($row); + + $sala_item=array( + "idsala" => $idsala, + "sala" => html_entity_decode($sala), + ); + + array_push($salas_arr["records"], $sala_item); + } + + // set response code - 200 OK + http_response_code(200); + + // show salas data in json format + echo json_encode($salas_arr); +}else{ + + // set response code - 404 Not found + http_response_code(404); + + // tell the user no products found + echo json_encode( + array("message" => "Nenhum sala encontrado.") + ); +} \ No newline at end of file diff --git a/api/shared/utilities.php b/api/shared/utilities.php new file mode 100644 index 000000000..d9b3b0946 --- /dev/null +++ b/api/shared/utilities.php @@ -0,0 +1,44 @@ +1 ? "{$page_url}page=1" : ""; + + // count all products in the database to calculate total pages + $total_pages = ceil(intval($total_rows) / $records_per_page); + + // range of links to show + $range = 2; + + // display links to 'range of pages' around 'current page' + $initial_num = $page - $range; + $condition_limit_num = ($page + $range) + 1; + + $paging_arr['pages']=array(); + $page_count=0; + + for($x=$initial_num; $x<$condition_limit_num; $x++){ + // be sure '$x is greater than 0' AND 'less than or equal to the $total_pages' + if(($x > 0) && ($x <= $total_pages)){ + $paging_arr['pages'][$page_count]["page"]=$x; + $paging_arr['pages'][$page_count]["url"]="{$page_url}page={$x}"; + $paging_arr['pages'][$page_count]["current_page"] = $x==$page ? "yes" : "no"; + + $page_count++; + } + } + + // button for last page + $paging_arr["last"] = $page<$total_pages ? "{$page_url}page={$total_pages}" : ""; + + // json format + return $paging_arr; + } + +} +?> \ No newline at end of file diff --git a/apiCursos.sql b/apiCursos.sql new file mode 100644 index 000000000..4eb483914 --- /dev/null +++ b/apiCursos.sql @@ -0,0 +1,157 @@ +-- phpMyAdmin SQL Dump +-- version 4.8.0.1 +-- https://www.phpmyadmin.net/ +-- +-- Host: 127.0.0.1 +-- Generation Time: 17-Nov-2018 às 13:18 +-- Versão do servidor: 10.1.30-MariaDB +-- PHP Version: 7.2.1 + +SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; +SET AUTOCOMMIT = 0; +START TRANSACTION; +SET time_zone = "+00:00"; + + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8mb4 */; + +-- +-- Database: `apidb` +-- +CREATE DATABASE IF NOT EXISTS `apicursos` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; +USE `apicursos`; + +-- -------------------------------------------------------- + +-- +-- Estrutura da tabela `cursos` +-- + +CREATE TABLE `cursos` ( + `idcurso` int(11) NOT NULL, + `curso` varchar(45) DEFAULT NULL, + `inico` varchar(4) DEFAULT NULL, + `fim` varchar(4) DEFAULT NULL, + `idprofessor` int(11) NOT NULL, + `idsala` int(11) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- -------------------------------------------------------- + +-- +-- Estrutura da tabela `professores` +-- + +CREATE TABLE `professores` ( + `idprofessor` int(11) NOT NULL, + `professor` varchar(45) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- -------------------------------------------------------- + +-- +-- Estrutura da tabela `salas` +-- + +CREATE TABLE `salas` ( + `idsala` int(11) NOT NULL, + `sala` varchar(45) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- -------------------------------------------------------- + +-- +-- Estrutura da tabela `usuarios` +-- + +CREATE TABLE `usuarios` ( + `idusuario` int(11) NOT NULL, + `usuario` varchar(45) DEFAULT NULL, + `senha` varchar(45) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- +-- Extraindo dados da tabela `usuarios` +-- + +INSERT INTO `usuarios` (`idusuario`, `usuario`, `senha`) VALUES +(1, 'admin@admin.com', '123456'); + +-- +-- Indexes for dumped tables +-- + +-- +-- Indexes for table `cursos` +-- +ALTER TABLE `cursos` + ADD PRIMARY KEY (`idcurso`,`idprofessor`,`idsala`), + ADD KEY `fk_cursos_professores_idx` (`idprofessor`), + ADD KEY `fk_cursos_salas1_idx` (`idsala`); + +-- +-- Indexes for table `professores` +-- +ALTER TABLE `professores` + ADD PRIMARY KEY (`idprofessor`); + +-- +-- Indexes for table `salas` +-- +ALTER TABLE `salas` + ADD PRIMARY KEY (`idsala`), + ADD UNIQUE KEY `sala_UNIQUE` (`sala`); + +-- +-- Indexes for table `usuarios` +-- +ALTER TABLE `usuarios` + ADD PRIMARY KEY (`idusuario`), + ADD UNIQUE KEY `usuario_UNIQUE` (`usuario`); + +-- +-- AUTO_INCREMENT for dumped tables +-- + +-- +-- AUTO_INCREMENT for table `cursos` +-- +ALTER TABLE `cursos` + MODIFY `idcurso` int(11) NOT NULL AUTO_INCREMENT; + +-- +-- AUTO_INCREMENT for table `professores` +-- +ALTER TABLE `professores` + MODIFY `idprofessor` int(11) NOT NULL AUTO_INCREMENT; + +-- +-- AUTO_INCREMENT for table `salas` +-- +ALTER TABLE `salas` + MODIFY `idsala` int(11) NOT NULL AUTO_INCREMENT; + +-- +-- AUTO_INCREMENT for table `usuarios` +-- +ALTER TABLE `usuarios` + MODIFY `idusuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; + +-- +-- Constraints for dumped tables +-- + +-- +-- Limitadores para a tabela `cursos` +-- +ALTER TABLE `cursos` + ADD CONSTRAINT `fk_cursos_professores` FOREIGN KEY (`idprofessor`) REFERENCES `professores` (`idprofessor`) ON DELETE NO ACTION ON UPDATE NO ACTION, + ADD CONSTRAINT `fk_cursos_salas1` FOREIGN KEY (`idsala`) REFERENCES `salas` (`idsala`) ON DELETE NO ACTION ON UPDATE NO ACTION; +COMMIT; + +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/index.php b/index.php new file mode 100644 index 000000000..df8bf0082 --- /dev/null +++ b/index.php @@ -0,0 +1,13 @@ + + + + +API Cursos + + + +Go to Login + + \ No newline at end of file diff --git a/pages/editar.php b/pages/editar.php new file mode 100644 index 000000000..998a531b1 --- /dev/null +++ b/pages/editar.php @@ -0,0 +1,191 @@ + + + + + + + + + + + API Cursos + + + + + +
+ +
+ +
Editar Detalhes do Curso
+
+ +
+
+
+ +
+ + + + + + + + + + + \ No newline at end of file diff --git a/pages/header.php b/pages/header.php new file mode 100644 index 000000000..d0f0cc511 --- /dev/null +++ b/pages/header.php @@ -0,0 +1,21 @@ + +
+
+
+ +
+
+
Sair
+
+
+ +
diff --git a/pages/index.php b/pages/index.php new file mode 100644 index 000000000..dce569a47 --- /dev/null +++ b/pages/index.php @@ -0,0 +1,96 @@ + + + + + + + + + + + API Cursos + + + +
+ + +
+
Cursos
+
+ +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/pages/inserir.php b/pages/inserir.php new file mode 100644 index 000000000..82f747f50 --- /dev/null +++ b/pages/inserir.php @@ -0,0 +1,151 @@ + + + + + + + + + + + + + API Cursos + + + +
+
+ +
+
Detalhes do Curso
+
+ +
+
+
+ +
+ + + + + + + + + + + \ No newline at end of file diff --git a/pages/login.php b/pages/login.php new file mode 100644 index 000000000..f343da215 --- /dev/null +++ b/pages/login.php @@ -0,0 +1,89 @@ + + + + + + + + + + + + API Cursos + + +
+ +
+
+
+
Login
+
+
+
+ + + +
+
+ + +
+ + +
+
+
+
+ + + + + + + + + + + \ No newline at end of file