Banner of None

Creating a real website with PHP object oriented - part 2 - connecting to mysql server


Category: php

Date: August 2020
Views: 1.57K


In the previous Article we talked about a few things to do when you are trying to make the first steps to make your website. In this tutorial we will make a class that will make the connection to our sql server. and all other classes will inherit it and extend it for mor features

For all our database operations we will use prepared statements as they are more secure against mysql injection. we will set the fetch mode for our PDO connection to allways be ASSOC as in associative arrays . so when we are selecting id,name,url, the data will be fetched in associative arrays as $row["id"], $row["name"], and $row["url"]; this way we won't confuse the rows when using them.

We will follow a naming convention for our classes to make it easy for us to autoload them into our index.php file in a simple and elegant way that I will show you in a later tutorial.

MAKING A DATABASE CONNECTION

the procedure is fairily simple:
Lets create our first php class file: in our resources/classes directory . we create Database.class.php File and we write the following php code:


//resources/classes/Database.class.php file
    class Database {
        protected $pdo;
        private $host="localhost";
        private $user="root";
        private $password="1313";

        public function __construct(){
            try{
                $this->pdo = new PDO("mysql:host".$this->host,$this->user,$this->password);
                $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
                $this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
                echo "we are connected";
            }catch(PDOException $e){
                echo $e->getMessage();
            }
        }
    }

the setAttribute methods will set the fetch mode to ASSOC and the error mode to exception, because sometimes we need to try to execute a PDO statement and we expect it to throw a PDO EXCEPTION like when inserting a value and we don't know it already exists, this way if the exception is thrown, we can then make a different query ( an UPDATE query for instance ).

and now we test our connection in our index.php file :


//index.php file
require_once "sources/classes/Database.class.php";
$d = new Database();

IF the "we are connected" message shows up then everything is OK and we are ready for the next step: a much bigger class to connect to our "wallpapers" database, this will be the subject of our next tutorial
In the mean time, As usual, here the video illustrating this tutorial:



1.57K views

Previous Article Next Article

1 Comments, latest

  • Ferne Klein
    12 months ago

    Enhance your new site's online presence with our free directory submission. https://rb.gy/drluwb