dongque8332 2012-11-19 21:31
浏览 38
已采纳

使PDO连接变量可在整个站点访问

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
  • 写回答

6条回答 默认 最新

  • douhao2153 2012-11-19 21:43
    关注

    First off, I strongly recommend you don't listen to anyone telling you to set it as global.


    Pass the connection object to the function, using an argument:

    exist_client_to_class(PDO $pdo, $cd) { //...
    

    That's a simplified version of what's called Dependency Injection.

    A more robust version includes by wrapping your functions into classes (and instantiating objects from those classes), and passing the PDO object (or some sort of Factory object) to the constructor of that object. Then it would be "globally" available throughout the methods (functions) of that object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料