Crear joins en base de datos

index.php:

 <h1>Camino entre tablas</h1>
        Escoja tabla:
        <form>
            <select name="bd">
                <?php
                $user = 'root';
                $pass = '';
                $server = 'localhost';

                $dbh = new PDO("mysql:host=$server", $user, $pass);
                $dbs = $dbh->query('SHOW DATABASES');

                while (( $db = $dbs->fetchColumn(0) ) !== false) {
                    echo "<option>".$db . '</option>';
                }
                ?>
            </select>
            <input type="submit" value="Enviar"></form>
        <?php
        if (!empty($_GET['bd'])){
            ?>
        <p>Seleccione las tablas origen y fin</p>
        <form action="camino.php">
            <input type="hidden" name="bd" value="<?=$_GET['bd']?>">
            <label>Origen:</label>
            <select name="origen">
                <?php
                 $dbs = $dbh->query('USE '.$_GET['bd']);
                 $dbs = $dbh->query('SHOW TABLES');
                 
                while (( $db = $dbs->fetchColumn(0) ) !== false) {
                    echo "<option>".$db . '</option>';
                }
                ?>
            </select>
            <label>Fin:</label>
            <select name="fin"><?php
                 $dbs = $dbh->query('USE '.$_GET['bd']);
                 $dbs = $dbh->query('SHOW TABLES');
                 
                while (( $db = $dbs->fetchColumn(0) ) !== false) {
                    echo "<option>".$db . '</option>';
                }
                ?></select>
             <input type="submit" value="Enviar">
        </form>
        <?php
        }

camino.php

<?php

$bd = $_GET['bd'];
$origen = $_GET['origen'];
$fin = $_GET['fin'];

$user = 'root';
$pass = '';
$server = 'localhost';

$dbh = new PDO("mysql:host=$server", $user, $pass);
$dbs = $dbh->query('use ' . $bd);

$tablas = getTables($dbh);
$tablas = setFKPaths($tablas, $dbh, $bd);

$caminos = [];
buscarCamino($origen, $fin, $origen, 0);
usort($caminos, function($a, $b) {
    return strlen($a) - strlen($b);
});
foreach ($caminos as $camino) {
    $camino = explode(",", $camino);
    echo "<h4>select * from " . $camino[0];
    for ($i = 1; $i < count($camino); $i++) {
        $c = explode("/", $camino[$i]);
        echo " join " . $c[0] . " using (" . $c[1] . ")<br/>";
    }
    echo "</h4>";
}

function getTables($dbh) {
    $tablas = [];
    $dbs = $dbh->query('SHOW TABLES');

    while (( $db = $dbs->fetchColumn(0) ) !== false) {
        $tablas[$db] = [];
    }
    return $tablas;
}

function setFKPaths($tablas, $dbh, $bd) {
    $dbs = $dbh->query("select * from information_schema.INNODB_SYS_FOREIGN where id like '$bd%'");
    $fks = $dbs->fetchAll();
    foreach ($fks as $fk) {
        $dbs = $dbh->query("select * from information_schema.INNODB_SYS_FOREIGN_COLS where id = '$fk[0]'");
        $fc = $dbs->fetchAll();
        $t1 = explode("/", $fk[1])[1];
        $t2 = explode("/", $fk[2])[1];
        $k = $fc[0][1];
        if (!in_array($t1 . "/" . $k, $tablas[$t2])) {
            $tablas[$t2][] = $t1 . "/" . $k;
        }
        if (!in_array($t2 . "/" . $k, $tablas[$t1])) {
            $tablas[$t1][] = $t2 . "/" . $k;
        }
    }
    return $tablas;
}



function buscarCamino($inicio, $fin, $camino, $prof) {
    global $caminos;
    global $tablas;

    if ($inicio == $fin) {
        $caminos[] = $camino;
        return;
    }
    foreach ($tablas[$inicio] as $destino) {
        $d = explode("/", $destino)[0];
        if (strpos($camino, "," . $d . "/") === false && strpos($camino, $d . ",") === false) {
            buscarCamino($d, $fin, $camino . "," . $destino, $prof + 1);
        }
    }
}

Mantenimento actores

sakila.php

<?php

class Sakila {

private $server = "localhost";
 private $user = "root";
 private $password = "";
 private $db = "sakila";
 public $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 getActors() {
 $sql = "select * from actor";
 $query = $this->conn->query($sql);
 return $query->fetchAll();
 }

function getActor($id) {
 $sql = "select * from actor where actor_id=$id";
 $query = $this->conn->query($sql);
 return $query->fetch();
 }

/**
 * 
 * @param type $actor array asociativo con los campos del actor
 * ejemplo: ['actor_id'=>1,'first_name'=>'Santiago','last_name'=>'Segura']
 */
 function updateActor($actor) {
 $sql = "update actor set first_name='" . $actor['first_name'] . "', last_name='" . $actor['last_name'] . "'
 where actor_id=" . $actor['actor_id'] . ";";
 $this->conn->exec($sql);
 }

function deleteActor($id) {
 $sql = "delete from actor where actor_id=$id";
 $this->conn->exec($sql);
 }

/**
 * 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";
 $st = $this->conn->prepare($sql);
 $st->execute([':first_name' => $first_name, ':last_name' => $last_name]);
 if ($actor = $st->fetch()) {
 return $actor['actor_id'];
 }
 $sql = "insert into actor (first_name,last_name) values (:first_name,:last_name)";
 $st = $this->conn->prepare($sql);
 $st->execute([':first_name' => $first_name, ':last_name' => $last_name]);
 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) {

$this->conn->beginTransaction();
 try {
 $sql = "insert into film(title,language_id) values (:film,1)";
 $st = $this->conn->prepare($sql);
 $st->execute([':film' => $film]);
 $film_id = $this->conn->lastInsertId();
 $sql = "insert into film_category(film_id,category_id) values($film_id,$category_id)";
 $this->conn->exec($sql);
 $this->conn->commit();
 } catch (PDOException $e) {
 echo $e->getMessage();
 $this->conn->rollBack();
 }
 }

/**
 * 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
 }

}

index.php

<!DOCTYPE html>

<html>
 <head>
 <meta charset="UTF-8">
 <title></title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">

</head>
 <body>
 <div class="container">
 <?php
 include "sakila.php";
 $sakila = new Sakila();

$nuevo = filter_input(INPUT_GET, 'nuevo');
 $first_name = filter_input(INPUT_GET, 'first_name');
 $last_name = filter_input(INPUT_GET, 'last_name');

if (!empty($nuevo) && !empty($first_name) && !empty($last_name)) {
 $sakila->newActor($first_name, $last_name);
 }
 $cambiar = filter_input(INPUT_GET, 'cambiar');
 $actor_id = filter_input(INPUT_GET, 'actor_id');

if (!empty($cambiar) && !empty($actor_id) && !empty($first_name) && !empty($last_name)) {
 $sakila->updateActor(['actor_id' => $actor_id, 'first_name' => $first_name, 'last_name' => $last_name]);
 }

$delete = filter_input(INPUT_POST, 'delete');
 $actor_id = filter_input(INPUT_POST, 'actor_id');

if (!empty($delete) && !empty($actor_id)) {
 $sakila->deleteActor($actor_id);
 }


 $actores = $sakila->getActors();
 ?>
 <h1>Mantenimiento actores</h1>

<form>
 <div class="form-group">
 <label for="first_name">Nombre:</label>
 <input type="text" class="form-control" name="first_name">
 </div>
 <div class="form-group">
 <label for="last_name">Apellidos:</label>
 <input type="text" class="form-control" name="last_name">
 </div>
 <input class="btn btn-success" type="submit" name="nuevo" value="Nuevo">
 </form>
 <table class="table">
 <tr><td>Nombre</td><td>Apellidos</td><td>Acciones</td></tr>
 <?php
 foreach ($actores as $actor) {
 ?>
 <tr><td><?= $actor['first_name'] ?></td><td><?= $actor['last_name'] ?></td>
 <td><a href="editar.php?actor_id=<?= $actor['actor_id'] ?>" class="btn btn-success">Editar</a>
 <form action="index.php" method="post" style="float:left;margin-right: 10px">
 <input type="hidden" name="actor_id" value="<?= $actor['actor_id'] ?>">
 <input class="btn btn-success" type="submit" name="delete" value="Borrar"> 
 </form>
 </td></tr>
 <?php
 }
 ?>
 </table>
 </div>
 </body>
</html>

editar.php

<!DOCTYPE html>

<html>
 <head>
 <meta charset="UTF-8">
 <title></title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">

</head>
 <body>
 <div class="container">
 <?php
 include "sakila.php";
 $sakila = new Sakila();


 $actor_id = filter_input(INPUT_GET, 'actor_id');

if (!empty($actor_id)) {
 $actor = $sakila->getActor($actor_id);
 }
 ?>
 <h1>Editar actor</h1>

<form action="index.php">
 <input type="hidden" class="form-control" name="actor_id" value="<?= $actor['actor_id'] ?>">
 <div class="form-group">
 <label for="first_name">Nombre:</label>
 <input type="text" class="form-control" name="first_name" value="<?= $actor['first_name'] ?>">
 </div>
 <div class="form-group">
 <label for="last_name">Apellidos:</label>
 <input type="text" class="form-control" name="last_name" value="<?= $actor['last_name'] ?>">
 </div>
 <input class="btn btn-success" type="submit" name="cambiar" value="Cambiar">
 </form>
 </div>
 </body>
</html>

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
 }

}

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>

Añadir película y categoría

<?php
 $server = "localhost";
 $user = "root";
 $password = "";
 $db = "sakila";

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

$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
 $conn->exec("SET CHARACTER SET utf8");

$category = filter_input(INPUT_GET, "category", FILTER_VALIDATE_INT);
 $film = filter_input(INPUT_GET, "film");
 if (!empty($category) && !empty($film)) {
 $sql="insert into film(title,language_id) values ('$film',1)";
 $conn->exec($sql);
 $film_id=$conn->lastInsertId();
 $sql="insert into film_category(film_id,category_id) values($film_id,$category)";
 $conn->exec($sql);
 }

$sql = "select * from category";
 $q = $conn->query($sql);
 $categorias = $q->fetchAll();
 } catch (PDOException $e) {
 echo "Connection failed: " . $e->getMessage();
 }
 ?>
 <form>
 Categoría: 
 <select name="category">
 <?php foreach ($categorias as $categoria) {
 ?>
 <option value="<?= $categoria['category_id'] ?>"><?= $categoria['name'] ?></option>
 <?php } ?>
 </select>
 <br/>
 Película: <input type="text" name="film"><br/>
 <input type="submit">

</form>

Ejemplos __get y __set y herencia

<?php

class Empleado {

private $nombre;
 private $sueldo;

function __construct($nombre, $sueldo) {
 $this->nombre = $nombre;
 }

function paga() {
 return $this->sueldo / 12;
 }

public function __get($propiedad) {
 if (property_exists($this, $propiedad)) {
 return $this->$propiedad;
 } else {
 throw new Exception("No existe la propiedad");
 }
 }

public function __set($property, $value) {
 if (property_exists($this, $property)) {
 if ($property == "sueldo") {
 if ($value > 600) {
 $this->sueldo = $value;
 } else {
 throw new Exception("Sueldo debe ser > 600");
 }
 } elseif (!empty($value)) {
 $this->$property = $value;
 }
 }
 }

}

class comercial extends empleado {

private $comision = .1;
 protected $ventas;

public function __construct($nombre, $sueldo, $ventas) {
 parent::__construct($nombre, $sueldo);
 $this->ventas = $ventas;
 }

function paga() {
 $p = parent::paga();
 return $p + $this->ventas * $this->comision / 12;
 }

}

index.php

$juan = new Empleado("Juan", 300);
        $p=new comercial("Juasdan", 300,9000);
        echo $p->nombre;
        echo $p->paga();
        try {
            $juan->sueldo = 6000;
            echo $juan->sueldo;
            echo $juan->paga();
        } catch (Exception $error) {
            echo $error->getMessage();
        }

Cesta de la compra con clases

cesta.php:

<?php

class cesta {

private $cesta = [];

function anyadir($producto,$precio){
 $this->cesta[]=['producto'=>$producto,'precio'=>$precio];
 }
 function verCesta() {
 ?>
 <table border="1">
 <tr><td>Producto</td><td>Precio</td></tr>
 <?php foreach ($this->cesta as $elemento) {
 ?>
 <tr><td><?= $elemento['producto'] ?></td><td><?= $elemento['precio'] ?></td>
 </tr> <?php } ?>
 </table> <?php
 }

}

index.php

<?php
 include_once "cesta.php";
 session_start();
 if (!isset($_SESSION['cesta'])) {
 $_SESSION['cesta'] = new cesta();
 }
 $producto = filter_input(INPUT_GET, 'producto');
 $precio = filter_input(INPUT_GET, 'precio', FILTER_VALIDATE_INT);
 if (!empty($producto) && !empty($precio)) {
 $_SESSION['cesta']->anyadir($producto, $precio);
 }
 $_SESSION['cesta']->verCesta();
 
 ?>

<form>
 <p>Producto:<input type="text" name="producto"></p>
 <p>Precio:<input type="text" name="precio"></p>
 <input type="submit">
 </form>

 

Operador resolución de ámbito (::)

<?php

class ClaseSencilla {

// Declaración de una propiedad
 public $var = 'un valor predeterminado';
 static $nombre = "Clase";

// Declaración de un método
 public function mostrarVar() {
 echo $this->var;
 }

public function __construct($var = "Instancia por defecto") {
 $this->var = $var;
 }

public function __destruct() {
 //Si hay algo que destruir
 }

static function hola() {
 echo "Hola que tal";
 }

}

ClaseSencilla::hola();

echo ClaseSencilla::$nombre;

class MyClass {

protected function myFunc() {
 echo "MyClass::myFunc()\n";
 }

}

class OtherClass extends MyClass {

// Sobrescritura de definición parent
 public function myFunc() {
 // Pero todavía se puede llamar a la función parent
 parent::myFunc();
 echo "OtherClass::myFunc()\n";
 }

}

$class = new OtherClass();
 $class->myFunc();
 ?>

Ejemplos clases

<?php

class ClaseSencilla {

// Declaración de una propiedad
 public $var = 'un valor predeterminado';

// Declaración de un método
 public function mostrarVar() {
 echo $this->var;
 }

public function __construct($var = "Instancia por defecto") {
 $this->var = $var;
 }

public function __destruct() {
 //Si hay algo que destruir
 }

}

$instancia = new ClaseSencilla("Instancia 1");
 $instancia->mostrarVar();

$otraInstancia = new ClaseSencilla("Instancia 2");
 $otraInstancia->mostrarVar();

$otraMas = new ClaseSencilla();
 $otraMas->mostrarVar();

//Visibilidad

/**
 * Definición de MyClass
 */
 class MyClass {

public $variablePublica = 'Public';
 protected $variableProtegida = 'Protected';
 private $variablePrivada = 'Private';

function printHello() {
 echo $this->variablePublica;
 echo $this->variableProtegida;
 echo $this->variablePrivada;
 }

}

$obj = new MyClass();
 echo $obj->variablePublica; // Funciona bien
 //echo $obj->variableProtegida; // Error Fatal
 //echo $obj->variablePrivada; // Error Fatal
 $obj->printHello(); // Muestra Public, Protected y Private

/**
 * Definición de MyClass2
 */
 class MyClass2 extends MyClass {

// Se pueden redeclarar las propiedades pública y protegida, pero no la privada
 public $public = 'Public2';
 //protected $protected = 'Protected2';

function printHello() {
 echo $this->public;
 echo $this->protected;
 // echo $this->private; // Undefined
 }

}

$obj2 = new MyClass2();
 echo $obj2->public; // Funciona bien
 //echo $obj2->protected; // Error Fatal
 //echo $obj2->private; // Undefined
 $obj2->printHello(); // Muestra Public2, Protected2, Undefined
 ?>