Search code examples
phpdatabasemysqlilocalhost

PHP can't connect to database with mysqli_connect


i'm facing with this problem that when i'm trying connect to database with constants, then it's showing this in my VS editor: Undefined constant 'DB_HOST', 'DB_USER', 'DB_PASS', 'DB_NAME'.

Here my code:

<?php

$db['db_host'] = "localhost";
$db['db_user'] = "root";
$db['db_pass'] = "";
$db['db_name'] = "cms";

foreach($db as $key => $value){
     define(strtoupper($key), $value);
}

$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

?>

I tried change

$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

to

$connection = mysqli_connect('DB_HOST', 'DB_USER', 'DB_PASS', 'DB_NAME');

After this step, my localhost was showing this error below:

Warning: mysqli_connect(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\cms\includes\db.php on line 12

Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\cms\includes\db.php on line 12

Could you please help me solve this error, or tell me what i'm doing wrong


Solution

  • it seems to be an issue with the Visual Studio Code. The code works and connects to the db OK but shows DB_HOST etc as undefined with a wiggly red 'naughty' line. So I got rid of the warning by defining the constants without a loop or associative array.

    define("DB_HOST", 'localhost');
    define("DB_USER", 'root');
    define("DB_PASS", '');
    define("DB_NAME", 'cms');