davidlienhard/database
🐘 php library for easy access to databases
Setup
You can install through composer
with:
composer require davidlienhard/database:^2
Note: davidlienhard/database requires PHP 8.2
Examples
Connect to the Database-Server
<?php declare(strict_types=1);
use DavidLienhard\Database\Exception as DatabaseException;
use DavidLienhard\Database\Mysqli;
try {
$db = new Mysqli;
$db->connect("hostname", "username", "password", "dbname");
} catch (DatabaseException $e) {
echo "unable to connect to the database host";
exit(1);
}
Simple Select Query
<?php declare(strict_types=1);
use DavidLienhard\Database\Mysqli;
$userResult = $db->query(
"SELECT
`userID`,
`userName`
FROM
`user`"
);
while ($userData = $userResult->fetch_assoc()) {
echo $userData['userID'].": ".$userData['userName'].PHP_EOL;
}
Select Query with User-Data
<?php declare(strict_types=1);
use DavidLienhard\Database\Mysqli;
use DavidLienhard\Database\Parameter as DBParam;
$userResult = $db->query(
"SELECT
`userID`,
`userName`
FROM
`user`
WHERE
`userLevel` = ? and
`userType` = ?",
new DBParam("i", $userLevel),
new DBParam("s", $userType)
);
while ($userData = $userResult->fetch_assoc()) {
echo $userData['userID'].": ".$userData['userName'].PHP_EOL;
}
Insert-Query
<?php declare(strict_types=1);
use DavidLienhard\Database\Exception as DatabaseException;
use DavidLienhard\Database\Mysqli;
use DavidLienhard\Database\Parameter as DBParam;
try {
$db->query(
"INSERT INTO
`user`
SET
`userName` = ?,
`userLevel` = ?,
`userType` = ?",
new DBParam("s", $userName),
new DBParam("i", $userLevel),
new DBParam("s", $userType)
);
} catch (DatabaseException $e) {
echo "unable to update table";
exit(1);
}
License
The MIT License (MIT). Please see LICENSE for more information.