MySQL connection to PHP

MySQL connection to PHP

To connect your MySQL Database to your PHP you need the connection data (host, port, name, password and charset) which is usually in a “config.php” file. Here’s an example:

PHP
<?php

return [
    "database" => [
        "host" => "127.0.0.1",
        "port" => "3306",
        "dbname" => "myapp",
        "charset" => "utf8mb4"
    ]
];

Then you will also need a “Database” PHP class like this:

PHP
<?php

namespace Core;

use PDO;

class Database
{
    public $connection;
    public $statement;

    public function __construct($config, $username = 'root', $password = '')
    {
        $dsn = 'mysql:' . http_build_query($config, '', ';');

        $this->connection = new PDO($dsn, $username, $password, [
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]);
    }

    public function query($query, $params = [])
    {
        $this->statement = $this->connection->prepare($query);

        $this->statement->execute($params);

        return $this;
    }

    public function get()
    {
        return $this->statement->fetchAll();
    }

    public function find()
    {
        return $this->statement->fetch();
    }

    public function findOrFail()
    {
        $result = $this->find();

        if (! $result) {
            abort();
        }

        return $result;
    }
}

Tags: