Access config.php variables

1

I am a beginner in php and I have a problem, I have a config.php file like this:

<?php
$config['dbHostname'] = 'localhost';
$config['dbUser'] = 'teste';
$config['dbPassword'] = 'passteste';

But I have a class with connection and database manipulation functions that would use these variables from config.php but I could not access them at all, please could anyone help me?

    
asked by anonymous 08.04.2014 / 05:35

4 answers

1

It would be one of the ways, in this case by the class constructor.

<?php

$config['dbHostname'] = 'localhost';
$config['dbUser'] = 'teste';
$config['dbPassword'] = 'passteste';

class Conexao
{
    private $pdo;
    public function __construct($config){
        $this->pdo = 
            new PDO("mysql:dbname=generics;host=".$config['dbHostname'], $config['dbUser'], $config['dbPassword']);
    }
}


$conexao = new Conexao($config);

?>
    
08.04.2014 / 05:42
1

You can access it by declaring the variable at the beginning of the function with the keyword global

public function mostrar1()
{
    global $txt;
    echo $txt;
}

Or use super-global $GLOBALS

public function mostrar2()
{
    $msg = $GLOBALS['txt'];
    echo $msg;
}

Example running link

Remembering that if you are programming using classes it is not very recommended to use global variables because they can cause conflicts, if you use them, copy the data that interests you and remove it from the global scope.

class Config
{
    /**
     * Configurações
     */
    var $safeconfig;

    public function __construct()
    {
        global $config;

        $this->safeconfig = $config;
        unset($config);
    }

    /**
     * Adicione aqui alguns setters e getters
     * para ter acesso as configurações
     */
}
    
08.04.2014 / 05:48
1

A simplified way to do this with just config.php would be:

<?php
    $config['dbHostname'] = 'localhost';
    $config['dbUser'] = 'teste';
    $config['dbPassword'] = 'passteste';
    $config['dbSchema'] = 'baseteste';

    $mysqli = new mysqli($config['dbHostname'],  $config['dbUser'], $config['dbPassword'], $config['dbSchema']);

    if (mysqli_connect_errno()) {
       printf("Falha na conexão: %s\n", mysqli_connect_error());
       exit();
    }

Any questions about using the mysqli function just look at official documentation

    
08.04.2014 / 15:59
0

Hello, use this following connection, you are probably not selecting the database use my connection but put the name of your database

<?php 
$servidor = "localhost";
$banco = "NOME DO BANCO DE DADOS AQUI";
$usuario = "teste";
$senha = "passteste";
$conexao = mysql_connect ($servidor, $usuario, $senha);
$conexao = mysql_select_db ("$banco", $conexao);
if (!$conexao) {
echo mysql_error; exit;
}
?>
    
08.04.2014 / 05:44