Añadir película y categoría con clases

sakila.php

<?php

class Sakila {

private $server = "localhost";
 private $user = "root";
 private $password = "";
 private $db = "sakila";
 private $conn;

function __construct() {
 try {
 $this->conn = new PDO("mysql:host=$this->server;dbname=$this->db", $this->user, $this->password);
 $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
 $this->conn->exec("SET CHARACTER SET utf8");
 
 } catch (PDOException $e) {
 echo "Connection failed: " . $e->getMessage();
 }
 }

function newFilm($category_id, $film) {
 
 $sql = "insert into film(title,language_id) values ('$film',1)";
 $this->conn->exec($sql);
 $film_id = $this->conn->lastInsertId();
 $sql = "insert into film_category(film_id,category_id) values($film_id,$category_id)";
 $this->conn->exec($sql);
 }

function selectCategory() {
 $sql = "select * from category";
 $q = $this->conn->query($sql);
 $categorias = $q->fetchAll();
 ?>
 <select name="category">
 <?php foreach ($categorias as $categoria) {
 ?>
 <option value="<?= $categoria['category_id'] ?>"><?= $categoria['name'] ?></option>
 <?php } ?>
 </select>
 <?php
 }

}

index.php

<?php
 include "sakila.php";
 $sakila = new Sakila();

$category = filter_input(INPUT_GET, "category", FILTER_VALIDATE_INT);
 $film = filter_input(INPUT_GET, "film");
 if (!empty($category) && !empty($film)) {
 $sakila->newFilm($category, $film);
 }
 ?>
 <form>
 Categoría: 
 <?php $sakila->selectCategory(); ?>
 <br/>
 Película: <input type="text" name="film"><br/>
 <input type="submit">

</form>

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos