0

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));
}


?>
  • You can't use constants like that in a string. See here: [Include constant in string without concatenating](https://stackoverflow.com/questions/2203943/include-constant-in-string-without-concatenating) – ficuscr Nov 01 '18 at 22:17
  • Correct. I guess I am having trouble using a variable in the sql code. I thought it was possible, but I might have misread something somewhere. – Michael Rice Nov 01 '18 at 22:18
  • The error message is a good clue. – ficuscr Nov 01 '18 at 22:18
  • Thank you for pointing me in the right direction. I was pretty sure the defining part was the area being mixed up. I'll figure out how to create the variable to add into the string. – Michael Rice Nov 01 '18 at 22:31

0 Answers0