juniorsabbath

create db/table with php script

May 31st, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.83 KB | None | 0 0
  1. <?php
  2. class Create_database
  3. {
  4.     protected $pdo;
  5.    
  6.     public function __construct()
  7.     {
  8.         $this->pdo = new PDO("mysql:host=servidor;", "root", "password");
  9.     }
  10.     //creamos la base de datos y las tablas que necesitemos
  11.     public function my_db()
  12.     {
  13.         //creamos la base de datos si no existe
  14.         $crear_db = $this->pdo->prepare('CREATE DATABASE IF NOT EXISTS nueva COLLATE utf8_spanish_ci');                          
  15.         $crear_db->execute();
  16.        
  17.         //decimos que queremos usar la tabla que acabamos de crear
  18.         if($crear_db):
  19.         $use_db = $this->pdo->prepare('USE nueva');                      
  20.         $use_db->execute();
  21.         endif;
  22.        
  23.         //si se ha creado la base de datos y estamos en uso de ella creamos las tablas
  24.         if($use_db):
  25.         //creamos la tabla usuarios
  26.         $crear_tb_users = $this->pdo->prepare('
  27.                         CREATE TABLE IF NOT EXISTS users (
  28.                         id int(11) NOT NULL AUTO_INCREMENT,
  29.                         name varchar(100) COLLATE utf8_spanish_ci NOT NULL,
  30.                         lastname varchar(150) COLLATE utf8_spanish_ci NOT NULL,
  31.                         username varchar(100) COLLATE utf8_spanish_ci NOT NULL,
  32.                         password varchar(100) COLLATE utf8_spanish_ci NOT NULL,
  33.                         email varchar(100) COLLATE utf8_spanish_ci NOT NULL,
  34.                         registro date NOT NULL,
  35.                         fecha datetime NOT NULL,
  36.                         PRIMARY KEY (id)
  37.                         )');                           
  38.         $crear_tb_users->execute();
  39.        
  40.         //creamos la tabla posts
  41.         $crear_tb_posts = $this->pdo->prepare('
  42.                         CREATE TABLE IF NOT EXISTS posts (
  43.                         id int(11) NOT NULL AUTO_INCREMENT,
  44.                         id_user int(11) NOT NULL,
  45.                         titulo varchar(255) COLLATE utf8_spanish_ci NOT NULL,
  46.                         contenido text COLLATE utf8_spanish_ci NOT NULL,
  47.                         fecha_post datetime NOT NULL,
  48.                         PRIMARY KEY (id)
  49.                         )');                           
  50.         $crear_tb_posts->execute();
  51.         endif;
  52.        
  53.     }
  54. }
  55. //ejecutamos la función my_db para crear nuestra bd y las tablas
  56. $db = new Create_database();
  57. $db->my_db();
  58. ?>
Advertisement
Add Comment
Please, Sign In to add comment