So essentially I'm creating a custom PHP function and class for handling PDO MySQL connections for me. I'm using this both to learn about creating my own classes/functions, and because I'd like to make it modular, i.e. I don't have to change sections of code when something may change later so it's readable (I'm still learning).
Here is the code. There may be a better way to differentiate between giving the variables and parsing the .ini, but I'm unsure how to do that in a single function, so I separated them.
<?php
class PDOMySQL
{
var $_Creds;
var $_PDO_Conn;
var $_Server_Name;
var $_DB_Name;
function ConnFile($_Creds_File)
{
$_Creds = parse_ini_file($_Creds_File);
$_PDO_Conn = new PDO // Create connection to MySQL Database.
(
"mysql:host=$_Creds['server'];dbname=$_Creds['database']",
$_Creds['username'],
$_Creds['password']
);
$_PDO_Conn->setAttribute
( // Prepare Attribute for Error Mode Exception Handling.
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
$_PDO_Conn->setAttribute
( // always disable emulated prepared statement when
// using the MySQL driver
PDO::ATTR_EMULATE_PREPARES, false
);
return $_PDO_Conn;
} // Function Ends
function ConnVar($_Server_Name,$_DB_Name,$_UserName,$_Password)
{
$_PDO_Conn = new PDO // Create connection to MySQL Database.
(
"mysql:host=$_Server_Name;dbname=$_DB_Name",
$_UserName,
$_Password
);
$_PDO_Conn->setAttribute
( // Prepare Attribute for Error Mode Exception Handling.
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
$_PDO_Conn->setAttribute
( // always disable emulated prepared statement when
// using the MySQL driver
PDO::ATTR_EMULATE_PREPARES, false
);
return $_PDO_Conn;
} // Function Ends
} // Class Ends
?>
The important bit:
$_PDO_Conn = new PDO // Create connection to MySQL Database.
(
"mysql:host=$_Creds['server'];dbname=$_Creds['database']",
$_Creds['username'],
$_Creds['password']
);
My question is regarding the mysql:host line. parse_ini_file
produces an associative array of whatever is set up in the .ini file. In this case, the ini file is like so:
[credentials]
server = <server>
database = <database>
username = <username>
password = <password>
How do I bypass the need for double quotes for the new PDO connection, or call the values with those keys in the array within double quotes?