Clase BD de acceso a datos

<?php

class BD {

    static $server = "localhost";
    static $user = "root";
    static $password = "";
    static $database = "sakila";
    private $table;
    static private $conn;

    public function __construct($table) {
        $this->table = $table;
        self::conectar();
    }

    static function conectar() {
        try {
            self::$conn = new PDO("mysql:host=" . self::$server . ";dbname=" . self::$database, self::$user, self::$password, [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"]);
            self::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    function getAll() {
        $res = self::$conn->query("select * from " . $this->table);
        return $res->fetchAll();
    }

    /**
     * Esta función nos devuelve el elemento de la tabla que tenga este id
     * @param int $id El id de la fila
     */
    function getById($id) {
        $res = self::$conn->query("select * from " . $this->table . " where "
                . $this->table . "_id=" . $id);
        return $res->fetch();
    }

    /**
     * Elimina el registro que tenga el id que le pasamos
     * @param int $id
     */
    function deleteById($id) {
        try {
            self::$conn->exec("delete from " . $this->table . " where "
                    . $this->table . "_id=" . $id);
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    /**
     * Esta función toma como parámetro un array asociativo y nos inserta en la tabla
     * un registro donde la clave del array hace referencia al campo de la tabla y
     * el valor del array al valor de la tabla.
     * ejemplo para la tabla actor: insert(['first_name'=>'Ana','last_name'=>'Pi'])
     * @param type $valores
     */
    function insert($valores) {
        try {
            $campos = join(",", array_keys($valores));
            $parametros = ":" . join(",:", array_keys($valores));
            $sql = "insert into " . $this->table . "($campos) values ($parametros)";
            $st = self::$conn->prepare($sql);
            $st->execute($valores);
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

}

$actores = new BD("actor");
//print_r($actores->getAll());

$paises = new BD("country");
//$paises->insert(['country'=>'Chiquitistán']);
//print_r($paises->getAll());
//print_r($actores->getById(1));

$v = ['first_name' => 'Ana', 'last_name' => 'Pimiento'];
$actores->insert($v);

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos