PDO issue with scope

Discussion in 'Coding Help' started by swordsinfo, May 28, 2014.

Tags:
  1. swordsinfo

    swordsinfo New Member

    Hi guys quick question.


    Just trying to implement the PDO object in PHP - but alas I hit a wall. I liek to keep all the functions in a seperate file called functions and it will have functions like checkuser() updateuser() deleteuser() - these exist in the functions.php. When creating the PDO object I create it in connect.php (so as If i need to change the db config moving the site)


    HOWEVER!!! the pdo object is not available in the scope of the checkuser() updateuser() deleteuser() in functions.php file. It seems it is outside the scope.


    Previously my function would be :


    function loadCaseInfo($va1, $var2)
    {
    $sqlQuery = "SELECT * from Record ";
    $result = mysql_query($sqlQuery);
    if (!$result) die("Error: " .mysql_error());
    if (mysql_num_rows($result)>=1) {
    $memberArray = mysql_fetch_assoc($result);
    return $memberArray;
    }


    The mysql_query was available across the board which made it simple. The PDO object however is not and I have been trying all sorts of ways to make it work like :


    class getDB {
    function createDB(){
    $handler = new PDO('mysql:'.DB_PDO_DB,DB_USER,DB_PASSWORD);
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


    return $handler;
    }
    }


    $db = new getDB();
    $statement = $db->createDB();
    $record = $statement->prepare("select * from users ");


    Im pretty sure this is the complete wrong way about going about it and want to know the "correct way" of dealing with PDO objects. I have tried to call print_r($handler) in checkuser() updateuser() deleteuser() but comes up blank however if I call it outside of these functiosn but within the functions.php file (which houses all these functions) it works?!?!?!? any ideas??


    B
     
  2. swordsinfo

    swordsinfo New Member

    ok so I have found a work around by using the global statement which makes the pdo object available in the function. Follow up code similar to


    defined('xxxxx') or die('Restricted access');
    include_once (APPLICATION_PATH . "/inc/db.inc.php"); //pdo connection defined as $handler


    function authenticate($username, $password) {
    global $handler; // imports the $handler pdo object and makes available for db access
    print_r($handler);
    if (empty($username) or empty($password)){
    header("Location: index.php?action=fieldserror");
    }


    My question still stands should I have global $handler defined in each of my functions or am I looking at this problem the wrong way round. I have been looking at classes as an alternative option but I still think I would have to create a new object each time I wanted to run one of the class functions?? Any suggestions I am at the wall at this stage
     

Share This Page