kqrmo
kqrmo

Reputation: 29

How can I connect to MySQLi with variables from config.php file?

I'm trying to make a MySQL & PHP based control panel for my community. And I've made a settings.php file with arrays with configs. I have class files for functions but there is MySQL function, which will not connect with data I've entered on settings.php..

I've tried other config file options, but none of them works...

on settings.php I have MySQL data like this:

$config['database']['host'] = "---"; 
$config['database']['user'] = "---";
$config['database']['password'] = "---";
$config['database']['database'] = "---";

And on userdata.php class file, where I'm trying to use those config variables I have:

$mysql = new mysqli($config['database']['host'], $config['database']['user'], $config['database']['password'], $config['database']['database']);

obviously, on userdata.php I have also required the settings.php..

I was expecting the output to be correct, but it shows only 'wrong MySQL data' errors...

Upvotes: 0

Views: 1602

Answers (2)

kqrmo
kqrmo

Reputation: 29

I got it working with settings.php file like:

$config = array (
'db_host' => 'xxx',
'db_user' => 'xxx',
'db_pass' => 'xxx',
'db_database' => 'xxx'

and userdata.php like:

include 'settings.php';

$host = $config['db_host'];
$user = $config['db_user'];
$pass = $config['db_pass'];
$database = $config['db_database'];

$mysql = new mysqli($host, $user, $pass, $database);

Upvotes: 1

Arif
Arif

Reputation: 997

you can try this way in connection.php file

<?php
include_once("path/config.php");

function OpenCon()
{
  $dbhost = $config['database']['host'];
  $dbuser = $config['database']['user'];
  $dbpass = $config['database']['password'];
  $db = $config['database']['db'];

  $conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". 
  $conn -> error);

  return $conn;
}

Upvotes: 0

Related Questions