1

For my school project I need to recover some information one database and associate with another database. But for that I want to use a ini file because if the log for connection of one data base change, I don't want to change it in the code.

My code is :

<?php
// On recupére les info dans fichier ini pour mySQL
//Get Information in ini for mySQL

$fichier = 'BDDconnexion.ini';

if(file_exists($fichier)){

$config = parse_ini_file($fichier,true);

$ip = "$config['mySQL'][ip]";
$port = "$config['mySQL'][port]";
$nomBDD = "config['mySQL'][nomBDD]";
$login = "$config['mySQL'][login]";
$password = "$config['mySQL'][password]";


}

// On se connecte à MySQL
//Connexion to MySQL
try {
$bdd = new PDO(mysql . ':host='.$ip.'dbname='.$nomBDD,$login,$password,array(PDO::ATTR_ERRMODE =>  PDO::ERRMODE_EXCEPTION));
    } 
catch (Exception $e) 
    {
     die('Erreur : '. $e->getMessage());
    }


?>

It is not working and i have this error message :

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\connectmySQL.php on line 14.

And the composition of my ini file is :

[mySQL]
ip="127.0.0.1"
port=4900
nomBDD=MagicCash
login="******"
password=""

Can someone help me ?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
M.Théo
  • 23
  • 4

1 Answers1

2

Basic PHP: You cannot have quoted array keys in a "-quoted string:

$ip = "$config['mySQL'][ip]";
               ^-----^--- incorrect

The following are proper syntax for such things:

$ip = "foo $arr[key] bar";
$ip = "foo {$arr['key']} bar"; // note the {}
$Ip = "foo " . $arr['key'] . " bar";

Also note that you're using a multidimensional array, which will also cause problems. PHP's parser is not greedy:

$foo['bar']['baz'] = 'qux';
echo "$foo[bar][baz]"; // output is "Array[baz]"

For multi-dimensional array variables in a "-quoted string, you MUST use the {} notation:

echo "{$foo['bar']['baz']}"; // outputs 'qux'

And of course, in the greater scheme, your variables don't need to be quoted AT ALL. These two statements

$foo = "$bar";
$foo = $bar;

are essentially functionally identical, except the "$bar" version forces PHP to create a new string, fill in the $bar value, then assign it to $foo. Sometimes this is desired if $bar is something OTHER than a string, but generally it's a waste of cpu cycles.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • So for my code work I need to change this line : $ip = "$config['mySQL'][ip]"; with that ? $ip = "foo $arr[ip] bar"; I don't understand what is "foo" "arr" and "bar", i'm not good at all for the moment in this.. – M.Théo Jan 28 '16 at 15:17
  • So I can write : $ip = "foo $config[mySQL][ip] bar"; for find the setting of my IP that I need for my connection in mySQL? – M.Théo Jan 28 '16 at 15:26
  • no, you just need `$ip = $config['mySQL']['ip']` – Marc B Jan 28 '16 at 15:27