├── README.md ├── bdd.sql ├── config └── Database.php ├── models ├── Categories.php └── Produits.php └── produits ├── creer.php ├── lire.php ├── lire_un.php ├── modifier.php └── supprimer.php /README.md: -------------------------------------------------------------------------------- 1 | # api-rest 2 | Live Coding "Créer une API Rest" 3 | -------------------------------------------------------------------------------- /bdd.sql: -------------------------------------------------------------------------------- 1 | -- phpMyAdmin SQL Dump 2 | -- version 4.9.0.1 3 | -- https://www.phpmyadmin.net/ 4 | -- 5 | -- Hôte : localhost:3306 6 | -- Généré le : sam. 14 sep. 2019 à 07:32 7 | -- Version du serveur : 5.7.24 8 | -- Version de PHP : 7.3.8 9 | 10 | SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 11 | SET AUTOCOMMIT = 0; 12 | START TRANSACTION; 13 | SET time_zone = "+00:00"; 14 | 15 | 16 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 17 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 18 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 19 | /*!40101 SET NAMES utf8mb4 */; 20 | 21 | -- 22 | -- Base de données : `api_rest` 23 | -- 24 | DROP DATABASE IF EXISTS `api_rest`; 25 | CREATE DATABASE IF NOT EXISTS `api_rest` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; 26 | USE `api_rest`; 27 | 28 | -- -------------------------------------------------------- 29 | 30 | -- 31 | -- Structure de la table `categories` 32 | -- 33 | 34 | DROP TABLE IF EXISTS `categories`; 35 | CREATE TABLE `categories` ( 36 | `id` int(11) NOT NULL, 37 | `nom` varchar(256) NOT NULL, 38 | `description` text NOT NULL, 39 | `created_at` datetime NOT NULL, 40 | `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 41 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 42 | 43 | -- 44 | -- Déchargement des données de la table `categories` 45 | -- 46 | 47 | INSERT INTO `categories` (`id`, `nom`, `description`, `created_at`, `updated_at`) VALUES 48 | (1, 'Mode', 'Catégorie pour tout ce qui est en rapport avec la mode.', '2019-06-01 00:32:07', '2019-08-30 15:34:33'), 49 | (2, 'Electronique', 'Gadgets, drones et plus.', '2018-06-03 02:34:11', '2019-01-30 16:34:33'), 50 | (3, 'Moteurs', 'Sports mécaniques', '2018-06-01 10:33:07', '2019-07-30 15:34:54'), 51 | (5, 'Films', 'Produits cinématographiques.', '2018-06-01 10:33:07', '2018-01-08 12:27:26'), 52 | (6, 'Livres', 'E-books, livres audio...', '2018-06-01 10:33:07', '2019-01-08 12:27:47'), 53 | (13, 'Sports', 'Articles de sport.', '2018-01-09 02:24:24', '2019-01-09 00:24:24'); 54 | 55 | -- -------------------------------------------------------- 56 | 57 | -- 58 | -- Structure de la table `produits` 59 | -- 60 | 61 | DROP TABLE IF EXISTS `produits`; 62 | CREATE TABLE `produits` ( 63 | `id` int(11) NOT NULL, 64 | `nom` varchar(32) NOT NULL, 65 | `description` text NOT NULL, 66 | `prix` decimal(10,0) NOT NULL, 67 | `categories_id` int(11) NOT NULL, 68 | `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, 69 | `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 70 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 71 | 72 | -- 73 | -- Déchargement des données de la table `produits` 74 | -- 75 | 76 | INSERT INTO `produits` (`id`, `nom`, `description`, `prix`, `categories_id`, `created_at`, `updated_at`) VALUES 77 | (65, 'Samsung Galaxy S 10', 'Le dernier né des téléphones Samsung', '899', 2, '2019-09-07 21:19:09', '2019-09-07 19:19:09'), 78 | (66, 'Habemus Piratam', 'Le livre à propos d\'un pirate informatique', '13', 6, '2019-09-07 21:21:11', '2019-09-07 19:21:11'); 79 | 80 | -- 81 | -- Index pour les tables déchargées 82 | -- 83 | 84 | -- 85 | -- Index pour la table `categories` 86 | -- 87 | ALTER TABLE `categories` 88 | ADD PRIMARY KEY (`id`); 89 | 90 | -- 91 | -- Index pour la table `produits` 92 | -- 93 | ALTER TABLE `produits` 94 | ADD PRIMARY KEY (`id`), 95 | ADD KEY `categories_id` (`categories_id`); 96 | 97 | -- 98 | -- AUTO_INCREMENT pour les tables déchargées 99 | -- 100 | 101 | -- 102 | -- AUTO_INCREMENT pour la table `categories` 103 | -- 104 | ALTER TABLE `categories` 105 | MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; 106 | 107 | -- 108 | -- AUTO_INCREMENT pour la table `produits` 109 | -- 110 | ALTER TABLE `produits` 111 | MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=67; 112 | 113 | -- 114 | -- Contraintes pour les tables déchargées 115 | -- 116 | 117 | -- 118 | -- Contraintes pour la table `produits` 119 | -- 120 | ALTER TABLE `produits` 121 | ADD CONSTRAINT `produits_ibfk_1` FOREIGN KEY (`categories_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 122 | COMMIT; 123 | 124 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 125 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 126 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 127 | -------------------------------------------------------------------------------- /config/Database.php: -------------------------------------------------------------------------------- 1 | connexion = null; 14 | 15 | try{ 16 | $this->connexion = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password); 17 | $this->connexion->exec("set names utf8"); 18 | }catch(PDOException $exception){ 19 | echo "Erreur de connexion : " . $exception->getMessage(); 20 | } 21 | 22 | return $this->connexion; 23 | } 24 | } -------------------------------------------------------------------------------- /models/Categories.php: -------------------------------------------------------------------------------- 1 | connexion = $db; 23 | } 24 | 25 | /** 26 | * Lecture des produits 27 | * 28 | * @return void 29 | */ 30 | public function lire(){ 31 | // On écrit la requête 32 | $sql = "SELECT c.nom as categories_nom, p.id, p.nom, p.description, p.prix, p.categories_id, p.created_at FROM " . $this->table . " p LEFT JOIN categories c ON p.categories_id = c.id ORDER BY p.created_at DESC"; 33 | 34 | // On prépare la requête 35 | $query = $this->connexion->prepare($sql); 36 | 37 | // On exécute la requête 38 | $query->execute(); 39 | 40 | // On retourne le résultat 41 | return $query; 42 | } 43 | 44 | /** 45 | * Créer un produit 46 | * 47 | * @return void 48 | */ 49 | public function creer(){ 50 | 51 | // Ecriture de la requête SQL en y insérant le nom de la table 52 | $sql = "INSERT INTO " . $this->table . " SET nom=:nom, prix=:prix, description=:description, categories_id=:categories_id, created_at=:created_at"; 53 | 54 | // Préparation de la requête 55 | $query = $this->connexion->prepare($sql); 56 | 57 | // Protection contre les injections 58 | $this->nom=htmlspecialchars(strip_tags($this->nom)); 59 | $this->prix=htmlspecialchars(strip_tags($this->prix)); 60 | $this->description=htmlspecialchars(strip_tags($this->description)); 61 | $this->categories_id=htmlspecialchars(strip_tags($this->categories_id)); 62 | $this->created_at=htmlspecialchars(strip_tags($this->created_at)); 63 | 64 | // Ajout des données protégées 65 | $query->bindParam(":nom", $this->nom); 66 | $query->bindParam(":prix", $this->prix); 67 | $query->bindParam(":description", $this->description); 68 | $query->bindParam(":categories_id", $this->categories_id); 69 | $query->bindParam(":created_at", $this->created_at); 70 | 71 | // Exécution de la requête 72 | if($query->execute()){ 73 | return true; 74 | } 75 | return false; 76 | } 77 | 78 | /** 79 | * Lire un produit 80 | * 81 | * @return void 82 | */ 83 | public function lireUn(){ 84 | // On écrit la requête 85 | $sql = "SELECT c.nom as categories_nom, p.id, p.nom, p.description, p.prix, p.categories_id, p.created_at FROM " . $this->table . " p LEFT JOIN categories c ON p.categories_id = c.id WHERE p.id = ? LIMIT 0,1"; 86 | 87 | // On prépare la requête 88 | $query = $this->connexion->prepare( $sql ); 89 | 90 | // On attache l'id 91 | $query->bindParam(1, $this->id); 92 | 93 | // On exécute la requête 94 | $query->execute(); 95 | 96 | // on récupère la ligne 97 | $row = $query->fetch(PDO::FETCH_ASSOC); 98 | 99 | // On hydrate l'objet 100 | $this->nom = $row['nom']; 101 | $this->prix = $row['prix']; 102 | $this->description = $row['description']; 103 | $this->categories_id = $row['categories_id']; 104 | $this->categories_nom = $row['categories_nom']; 105 | } 106 | 107 | /** 108 | * Supprimer un produit 109 | * 110 | * @return void 111 | */ 112 | public function supprimer(){ 113 | // On écrit la requête 114 | $sql = "DELETE FROM " . $this->table . " WHERE id = ?"; 115 | 116 | // On prépare la requête 117 | $query = $this->connexion->prepare( $sql ); 118 | 119 | // On sécurise les données 120 | $this->id=htmlspecialchars(strip_tags($this->id)); 121 | 122 | // On attache l'id 123 | $query->bindParam(1, $this->id); 124 | 125 | // On exécute la requête 126 | if($query->execute()){ 127 | return true; 128 | } 129 | 130 | return false; 131 | } 132 | 133 | /** 134 | * Mettre à jour un produit 135 | * 136 | * @return void 137 | */ 138 | public function modifier(){ 139 | // On écrit la requête 140 | $sql = "UPDATE " . $this->table . " SET nom = :nom, prix = :prix, description = :description, categories_id = :categories_id WHERE id = :id"; 141 | 142 | // On prépare la requête 143 | $query = $this->connexion->prepare($sql); 144 | 145 | // On sécurise les données 146 | $this->nom=htmlspecialchars(strip_tags($this->nom)); 147 | $this->prix=htmlspecialchars(strip_tags($this->prix)); 148 | $this->description=htmlspecialchars(strip_tags($this->description)); 149 | $this->categories_id=htmlspecialchars(strip_tags($this->categories_id)); 150 | $this->id=htmlspecialchars(strip_tags($this->id)); 151 | 152 | // On attache les variables 153 | $query->bindParam(':nom', $this->nom); 154 | $query->bindParam(':prix', $this->prix); 155 | $query->bindParam(':description', $this->description); 156 | $query->bindParam(':categories_id', $this->categories_id); 157 | $query->bindParam(':id', $this->id); 158 | 159 | // On exécute 160 | if($query->execute()){ 161 | return true; 162 | } 163 | 164 | return false; 165 | } 166 | 167 | } -------------------------------------------------------------------------------- /produits/creer.php: -------------------------------------------------------------------------------- 1 | getConnection(); 18 | 19 | // On instancie les produits 20 | $produit = new Produits($db); 21 | 22 | // On récupère les informations envoyées 23 | $donnees = json_decode(file_get_contents("php://input")); 24 | 25 | if(!empty($donnees->nom) && !empty($donnees->description) && !empty($donnees->prix) && !empty($donnees->categories_id)){ 26 | // Ici on a reçu les données 27 | // On hydrate notre objet 28 | $produit->nom = $donnees->nom; 29 | $produit->description = $donnees->description; 30 | $produit->prix = $donnees->prix; 31 | $produit->categories_id = $donnees->categories_id; 32 | 33 | if($produit->creer()){ 34 | // Ici la création a fonctionné 35 | // On envoie un code 201 36 | http_response_code(201); 37 | echo json_encode(["message" => "L'ajout a été effectué"]); 38 | }else{ 39 | // Ici la création n'a pas fonctionné 40 | // On envoie un code 503 41 | http_response_code(503); 42 | echo json_encode(["message" => "L'ajout n'a pas été effectué"]); 43 | } 44 | } 45 | }else{ 46 | // On gère l'erreur 47 | http_response_code(405); 48 | echo json_encode(["message" => "La méthode n'est pas autorisée"]); 49 | } -------------------------------------------------------------------------------- /produits/lire.php: -------------------------------------------------------------------------------- 1 | getConnection(); 18 | 19 | // On instancie les produits 20 | $produit = new Produits($db); 21 | 22 | // On récupère les données 23 | $stmt = $produit->lire(); 24 | 25 | // On vérifie si on a au moins 1 produit 26 | if($stmt->rowCount() > 0){ 27 | // On initialise un tableau associatif 28 | $tableauProduits = []; 29 | $tableauProduits['produits'] = []; 30 | 31 | // On parcourt les produits 32 | while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ 33 | extract($row); 34 | 35 | $prod = [ 36 | "id" => $id, 37 | "nom" => $nom, 38 | "description" => $description, 39 | "prix" => $prix, 40 | "categories_id" => $categories_id, 41 | "categories_nom" => $categories_nom 42 | ]; 43 | 44 | $tableauProduits['produits'][] = $prod; 45 | } 46 | 47 | // On envoie le code réponse 200 OK 48 | http_response_code(200); 49 | 50 | // On encode en json et on envoie 51 | echo json_encode($tableauProduits); 52 | } 53 | 54 | }else{ 55 | // On gère l'erreur 56 | http_response_code(405); 57 | echo json_encode(["message" => "La méthode n'est pas autorisée"]); 58 | } -------------------------------------------------------------------------------- /produits/lire_un.php: -------------------------------------------------------------------------------- 1 | getConnection(); 18 | 19 | // On instancie les produits 20 | $produit = new Produits($db); 21 | 22 | $donnees = json_decode(file_get_contents("php://input")); 23 | 24 | if(!empty($donnees->id)){ 25 | $produit->id = $donnees->id; 26 | 27 | // On récupère le produit 28 | $produit->lireUn(); 29 | 30 | // On vérifie si le produit existe 31 | if($produit->nom != null){ 32 | 33 | $prod = [ 34 | "id" => $produit->id, 35 | "nom" => $produit->nom, 36 | "description" => $produit->description, 37 | "prix" => $produit->prix, 38 | "categories_id" => $produit->categories_id, 39 | "categories_nom" => $produit->categories_nom 40 | ]; 41 | // On envoie le code réponse 200 OK 42 | http_response_code(200); 43 | 44 | // On encode en json et on envoie 45 | echo json_encode($prod); 46 | }else{ 47 | // 404 Not found 48 | http_response_code(404); 49 | 50 | echo json_encode(array("message" => "Le produit n'existe pas.")); 51 | } 52 | 53 | } 54 | }else{ 55 | // On gère l'erreur 56 | http_response_code(405); 57 | echo json_encode(["message" => "La méthode n'est pas autorisée"]); 58 | } -------------------------------------------------------------------------------- /produits/modifier.php: -------------------------------------------------------------------------------- 1 | getConnection(); 18 | 19 | // On instancie les produits 20 | $produit = new Produits($db); 21 | 22 | // On récupère les informations envoyées 23 | $donnees = json_decode(file_get_contents("php://input")); 24 | 25 | if(!empty($donnees->id) && !empty($donnees->nom) && !empty($donnees->description) && !empty($donnees->prix) && !empty($donnees->categories_id)){ 26 | // Ici on a reçu les données 27 | // On hydrate notre objet 28 | $produit->id = $donnees->id; 29 | $produit->nom = $donnees->nom; 30 | $produit->description = $donnees->description; 31 | $produit->prix = $donnees->prix; 32 | $produit->categories_id = $donnees->categories_id; 33 | 34 | if($produit->modifier()){ 35 | // Ici la modification a fonctionné 36 | // On envoie un code 200 37 | http_response_code(200); 38 | echo json_encode(["message" => "La modification a été effectuée"]); 39 | }else{ 40 | // Ici la création n'a pas fonctionné 41 | // On envoie un code 503 42 | http_response_code(503); 43 | echo json_encode(["message" => "La modification n'a pas été effectuée"]); 44 | } 45 | } 46 | }else{ 47 | // On gère l'erreur 48 | http_response_code(405); 49 | echo json_encode(["message" => "La méthode n'est pas autorisée"]); 50 | } -------------------------------------------------------------------------------- /produits/supprimer.php: -------------------------------------------------------------------------------- 1 | getConnection(); 18 | 19 | // On instancie les produits 20 | $produit = new Produits($db); 21 | 22 | // On récupère l'id du produit 23 | $donnees = json_decode(file_get_contents("php://input")); 24 | 25 | if(!empty($donnees->id)){ 26 | $produit->id = $donnees->id; 27 | 28 | if($produit->supprimer()){ 29 | // Ici la suppression a fonctionné 30 | // On envoie un code 200 31 | http_response_code(200); 32 | echo json_encode(["message" => "La suppression a été effectuée"]); 33 | }else{ 34 | // Ici la création n'a pas fonctionné 35 | // On envoie un code 503 36 | http_response_code(503); 37 | echo json_encode(["message" => "La suppression n'a pas été effectuée"]); 38 | } 39 | } 40 | }else{ 41 | // On gère l'erreur 42 | http_response_code(405); 43 | echo json_encode(["message" => "La méthode n'est pas autorisée"]); 44 | } --------------------------------------------------------------------------------