I am beginning to convert all old mysql_ functions to PDO and have a little trouble grasping this concept. I want to be able to access my PDO connection variable throughout my function pages so that it can be called as needed without making a connection script at the beginning of each function. I'll try to explain my setup as best as possible.
This is my init.php page that loads all required php pages. This page is included at the top of each of my pages, but not function pages.
init.php
<?php
session_start();
error_reporting(E_All);
require 'database/connect.php';
require 'functions/users.php';
require 'functions/general.php';
require 'functions/trainer.php';
?>
Here is my connect file that opens my db connection. Yes I have a mysql_connect
open as well because I can not disable all my other functions while converting all the others over to PDO.
connect.php
<?php
$connect_error = 'Sorry there is a problem with the database connection.';
mysql_connect('Localhost', 'customn7', 'I<3deadlifts!') or die($connect_error);
mysql_select_db('customn7_cm') or die($connect_error) or die($connect_error);
?>
<?php
//PDO database connect
$config['db'] = array(
'host' => 'Localhost',
'username' => 'customn7',
'password' => '********',
'dbname' => 'customn7_cm'
);
try {
$db = new PDO('mysql:host=' .$config['db']['host']. ';dbname=' .$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET CHARACTER SET utf8");
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
Here is my functions/trainer.php
where the function is written:
trainer.php
function exist_client_to_class($cd){
list($user_id, $class_id, $first_name, $last_name, $nickname) = explode('|', $cd);
try{
$stmt = $db->prepare('INSERT INTO clients
(`user_id`, class_id, first_name, last_name, nickname, date)
VALUES (:user_id, :class_id, :first_name, :last_name, :nickname, CURDATE())
');
$stmt->execute(array(
':user_id' => $user_id,
':class_id' => $class_id,
':first_name' => $first_name,
':last_name' => $last_name,
':nickname' => $nickname)
);
}
catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}
As of now I can not access my $db
variable from my trainers.php page. Can someone help me with this?
UPDATE
Here is the code that calls the function:
// Post Selected name to current class.
if (isset($_POST['exist_to_class'])){
if (empty($_POST['client_data']) === true){
$errors [] = 'You much select a client to be added to the class.';
} else {
if (isset($_POST['client_data']) && !empty($_POST['client_data']));
foreach ($_POST['client_data'] as $cd){
exist_client_to_class($db, $cd);
header('Location: view_class.php?class_id='.$class_id.' ');
} // foreach $cd
} // else
} //isset