First get the PDO connection out of the function as that will cause you nothing but headaches.
Here's an example of a generic PDO connection ->
<?php
$host = '127.0.0.1'; // or your database host
$db = 'your_database_name';
$user = 'your_database_username';
$pass = 'your_database_password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
// Use $pdo to perform database operations
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
I would put this in a configuration file maybe name it config.php file?
My example would entail explaining OOP, so maybe someone else will do a better example for you. But here is how I do it ->
$sql = "SELECT id, password FROM admins WHERE username =:username LIMIT 1";
$user = $this->retrieve_credentials($sql, $username);
if ($user && password_verify($password, $user['password'])) {
session_regenerate_id(); // prevent session fixation attacks
$_SESSION['user_id'] = $user['id'];
return true;
}
return false;
and little more code
protected function retrieve_credentials(string $sql, string $username): ?array
{
$stmt = $this->pdo->prepare($sql);
$stmt->execute(['username' => $username]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result !== false ? $result : null;
}