I'll try my best to explain the process hoped to achieve from the code and the error occurrence.
First, I am creating a database for each member who joins and wishes to store information. So I have the first connection to check for session log in and store the username, at which point I end the connection. The next connection goes into the root to create a user and database in SQL. After that, i try the third connection and receive the following error
Warning: mysqli_connect(): (HY000/1045): Access denied for user 'DB_USERNAME'@'localhost' (using password: YES) in C:\xampp\htdocs\managementportal.php on line 38
ERROR: Could not connect. Access denied for user 'DB_USERNAME'@'localhost' (using password: YES)
The sql query does not seem to be working in a way with which is creates a user/database and therefore there is nothing to connect which automatically gives me an error to connect.
PHP Code
<?php
$link = mysqli_connect("localhost", "php", "test", "php");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: members.php");
exit;
}
$username = trim($_SESSION['username']);
mysqli_close($link);
$slink = mysqli_connect('localhost', 'root', '');
define('DB_SERVER', 'localhost');
define('DB_USERNAME', '$username');
define('DB_PASSWORD', 'test');
define('DB_NAME', '$username');
$createdb = "CREATE USER IF NOT EXISTS 'DB_USERNAME'@'localhost' IDENTIFIED VIA mysql_native_password using 'DB_PASSWORD';
GRANT ALL PRIVELGES ON *.* TO 'DB_USERNAME'@'localhost'
REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR0 MAX_USER_CONNECTIONS 0;
CREATE DATABASE IF NOT EXISTS 'DB_NAME'; GRANT ALL PRIVILEGES ON 'DB_USERNAME' *.* TO 'DB_USERNAME'@'localhost'; " ;
mysqli_query($slink, $createdb);
mysqli_close($slink);
$ulink = mysqli_connect('localhost', 'DB_USERNAME', 'DB_PASSWORD', 'DB_NAME');
if($ulink === false){
die("ERROR: Could not connect. " . mysqli_connect_error($ulink));
}
?>