Part on DatabaseClass finished

This commit is contained in:
Patryk Hegenberg 2022-12-13 17:41:49 +01:00
parent 0806411f09
commit 57abb48e63
2 changed files with 22 additions and 13 deletions

18
Database.php Normal file
View file

@ -0,0 +1,18 @@
<?php
// connect to MySQL database.
class Database {
public $connection;
public function __construct()
{
$dsn = "mysql:host=localhost;port=3306;dbname=myapp;charset=utf8mb4";
$username = 'appUser';
$password = 'password';
$this->connection = new PDO($dsn, $username, $password);
}
public function query($query) {
$statement = $this->connection->prepare($query);
$statement->execute();
return $statement;
}
}

View file

@ -1,18 +1,9 @@
<?php
require 'functions.php';
require 'Database.php';
//require 'router.php';
// connect to MySQL database.
$dsn = "mysql:host=localhost;port=3306;dbname=myapp;charset=utf8mb4";
$username = 'appUser';
$password = 'password';
$pdo = new PDO($dsn, $username, $password);
$statement = $pdo->prepare("SELECT * FROM posts");
$statement->execute();
$db = new Database();
$posts = $db->query("SELECT * FROM posts")->fetchAll(PDO::FETCH_ASSOC);
$posts = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($posts as $post) {
echo "<li>" . $post['title'] . "</li>";
}
dd($posts);