- Forums
- PHP
- Php8- Simple Initial Database Connection Setup
this shows the php code you need to use to start a database connection with PHP8 [5327], Last Updated: Sun Mar 02, 2025
edw
Sun Mar 02, 2025
0 Comments
130 Visits
Today I am focusing on PHP8, This is the way to start a databse connection with PHP. For this example I am using Mysql/mariaSQL.
Structure:
includes > dbh.inc.php
index.php
dbh.inc.php
$dsn = 'mysql:host=localhost;dbname=forum';
$dbusername = 'root';
$dbpassword = '';
try {
$pdo == new PDO($dsn, $dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\Throwable $th) {
echo 'Connection failed: ' . $th->getMessage();
}
INSERT.php
// USING NAME PARAMETER INSTEAD OF QUESTION MARKS
try {
include_once 'dbh.inc.php';
// the order you enter the values in the array is the order you put the question marks in the sql statement
$sql = "INSERT INTO posts (title, content) VALUES (:title, :content)";
$stmt = $pdo->prepare($sql);
$stmt->execute(['title' => $_POST['title'], 'content' => $_POST['content']]);
echo 'Post added';
$pdo = null;
$stmt = null;
die();
} catch (\Throwable $th) {
echo 'Insert failed: ' . $th->getMessage();
}
SELECT.php
// SELECT.php
try {
include_once 'dbh.inc.php';
$sql = "SELECT * FROM posts";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$posts = $stmt->fetchAll();
$pdo = null;
$stmt = null;
die(json_encode($posts));
} catch (\Throwable $th) {
echo 'Select failed: ' . $th->getMessage();
}
// SELECT WHERE
try {
include_once 'dbh.inc.php';
$sql = "SELECT * FROM posts WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$_POST['id']]);
$post = $stmt->fetch();
$pdo = null;
$stmt = null;
die(json_encode($post));
} catch (\Throwable $th) {
echo 'Select failed: ' . $th->getMessage();
}
UPDATE.php
// UPDATE
try {
include_once 'dbh.inc.php';
$sql = "UPDATE posts SET title = :title, content = :content WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(['title' => $_POST['title'], 'content' => $_POST['content'], 'id' => $_POST['id']]);
echo 'Post updated';
$pdo = null;
$stmt = null;
die();
} catch (\Throwable $th) {
echo 'Update failed: ' . $th->getMessage();
}
DELETE.php
// DELETE
try {
include_once 'dbh.inc.php';
$sql = "DELETE FROM posts WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$_POST['id']]);
echo 'Post deleted';
$pdo = null;
$stmt = null;
die();
} catch (\Throwable $th) {
echo 'Delete failed: ' . $th->getMessage();
}
l4_Vn-sTBL8
Resource: https://youtu.be/l4_Vn-sTBL8?si=McwXEmdrwFUtTYDF&t=21132