Ejemplo conexión BD

<?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();
    }
}
$actores=new BD("actor");
print_r($actores->getAll());

$paises=new BD("country");

print_r($paises->getAll());

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos