Clase sakila

<?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();
 }
 }

/**
 * Inserta un nuevo actor o devuelve el id si ya existe
 * @param string valor de first_name
 * @param string valor de last_name
 * @return int id
 */
 function newActor($first_name, $last_name) {
 if (!empty($first_name) && !empty($last_name)) {
 $sql = "select * from actor where first_name='$first_name' and last_name='$last_name'";
 $c = $this->conn->query($sql);
 if ($actor = $c->fetch()) {
 return $actor['actor_id'];
 }
 $sql = "insert into actor (first_name,last_name) values ('$first_name','$last_name')";
 $this->conn->exec($sql);
 return $this->conn->lastInsertId();
 } else {
 return null;
 }
 }

/**
 * Inserta una película en una categoría
 * @param int id de la categoría
 * @param string título de la película
 */
 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);
 }

/**
 * Crea un select con todas las categorías
 */
 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
 }

}

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos