Skip to content

Instantly share code, notes, and snippets.

@sroehrl
Last active April 3, 2020 20:32
Show Gist options
  • Save sroehrl/f41cb71b30bd9834ca6147c0b2d0f6ec to your computer and use it in GitHub Desktop.
Save sroehrl/f41cb71b30bd9834ca6147c0b2d0f6ec to your computer and use it in GitHub Desktop.
<?php
// assumes existence of 'config.php'
require_once 'config.php';
/**
* Class Database
*/
class Database
{
/**
* @var mysqli
*/
private $connection;
/**
* @var
*/
public $some;
/**
* Database constructor.
*/
function __construct()
{
// set connection: use global constants as defined in "config.php"
$this->connection = new mysqli(db_host, db_user,db_password,'esl_parent');
// catch error
if($this->connection->connect_errno){
// if the connection to the db did not work, maybe the database doesn't exist? Let's try
$this->createDb();
}
// set public property
$this->some = 'readable';
}
/**
* Mock method
*/
function createDb()
{
// your existing create db function
}
/**
* Mock method 2
*/
private function getMe()
{
// only work in current $this
}
}
/*
* About using classes
* */
// creates an instance of "Database"
// $any now IS an instance of Database ...
$any = new Database();
// ... and can call all public methods & access public properties
// e.g. calling the createDb method
$any->createDb();
// or accessing public properties
echo $any->some;
// however, private methods & properties cannot be accessed
// $any->connection would fail
// $any->getMe() would fail
<?php
/*
* Where ever this file is included/required,
* the global constants will be available
* e.g.
* // output: localhost!
* echo db_host . '!';
*
* */
// please set local variables
define('db_host', 'localhost');
define('db_user', 'root');
define('db_password', '');
<?php
/*
* Another option is to provide an installation script for your application
* Installation steps would usually be explained in a README.md file
*/
require 'databasescript.php';
$db = new objDatabaseConnetction();
$db->CreateDB();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment