· 6 years ago · Dec 20, 2019, 01:56 AM
1<?php
2class dbConfig {
3 public $host;
4 public $username;
5 public $password;
6 public $dab;
7 public $conn;
8
9public function dbConnect (){
10 $this->conn = mysqli_connect ($this->host,$this->
11 username,$this->password);
12
13 if (!$this->conn){
14 die("Connection failed: " . mysqli_connect_error())
15;
16 }
17else {
18 echo "Connected successfully to server";
19}
20$db_selected = mysqli_select_db($this->conn, $this->dab);
21if (!$db_selected) {
22 // if the given database doesn't exists
23 // creates new database with that name
24 $db_sql = 'CREATE DATABASE chatapp';
25
26 // verify the database is created
27 if (mysqli_query($this->conn, $db_sql)){
28 echo "Database chatapp already exists or created successfully/n";
29 }else {
30 echo 'Error creating database: ' . mysqli_error() . "\n";
31 }
32}
33
34// creating tables
35$table_sql = "CREATE TABLE IF NOT EXISTS users (".
36"uid INT PRIMARY KEY AUTO_INCREMENT,".
37"username VARCHAR (30) UNIQUE,".
38"password VARCHAR (50) ,".
39"name VARCHAR (100),".
40"email VARCHAR (70) UNIQUE) ; ";
41
42//verify the table is created
43if (mysqli_query($this->conn, $table_sql)) {
44 echo "Table: users already exists or created successfully\n";
45} else {
46 echo 'Error creating table: ' . mysqli_error($table_sql) . "\n";
47 }
48}
49}
50
51$obj = new dbConfig ();
52
53$obj->host = 'localhost';
54$obj->username = 'root';
55$obj->password = '';
56$obj->dab= 'chatapp';
57$obj->dbConnect();
58?>