Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Simple PHP Class That interacts with a database object
- */
- /**
- * This is the database wrapper we will use to interact with the database object
- * known as `PDO`.
- */
- class Database
- {
- /**
- * This is the database variable that stores are PDO object.
- * The PDO object is the main object that will communicate to the database server.
- * I made the database object protected, as this allows/forces me to write clean,
- * and safe code, by forcing all database logic to be executed from the Database
- * class itself.
- *
- * The variable name is not important, it could be pdo, or instance.
- */
- protected $database;
- /**
- * This is the database constructor that will initialize are connection
- * to the database server.
- *
- * @param hostname. This is the hostname/ip address/domain the mysql server is located at.
- * @param username. This is the username that is allowed to connect to the database server.
- * @param password. This is the password for the username.
- * @param database. This is the name of the database we wanna connect to and use.
- */
- public function __construct($hostname = '127.0.0.1', $username = 'guest', $password = '', $database = 'testdb')
- {
- /**
- * The PDO driver expects a dns string that tells the driver what database
- * server we are using, the database name, and the hostname itself.
- *
- * PHP Strings can append other strings with . seperating the strings.
- */
- $dns = 'mysql:dbname=' . $database . ';host=' . $hostname;
- /**
- * Another way we can achievement this is with using a function called sprintf
- * which is a string formatting buffer.
- * The formated string will be 'mysql:dbname=%s;hostname=%s'.
- * The '%s' is telling sprintf that the first and second variable will be a string.
- * sprintf also allows integers, or decimals using '%d'.
- */
- $formatted_dns = sprintf('mysql:dbname=%s;host=%s', $database, $hostname);
- /**
- * Unlike the `mysqli` driver PDO will try to initialize, and if it can't it will throw an
- * exception, To catch the exception we have to use a try block in php.
- */
- try {
- /**
- * $this-> is an accessor for variables declared inside the class object/scope.
- * $this-> can access variables or functions also known as methods inside an object.
- *
- * PDO expects 3 variables at least, usually. The first being the dns string.
- * The second and third being the username and password.
- */
- $this->database = new PDO($formatted_dns, $username, $password);
- } catch (PDOException $exception) {
- /**
- * If the database could not be connected to for any reason,
- * like the server being down, or the PDO driver not being installed
- * an exception will be thrown.
- */
- echo 'The database connection failed: ' . $exception->getMessage();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement