php - PDO object not in scope of a function -


ok, see similar questions mine, examples use php classes...mine not. maybe that's problem? shouldn't need classes because site exceedingly simple @ point in time.

anyway, i'm trying use pdo connect mysql db. connect db fine in file called config.php, , include file in index.php require_once().

i can query db file called process.php, problem within function within file; seems dbo object out of scope within function.

here relevant code snippets:

index.php

require_once('./lib/config.php'); 

config.php

// tested , connects fine     $pdo = new pdo('mysql:host=' . $hostname . ';dbname=' . $dbname, $username, $password, array(     pdo::attr_persistent => true )); 

process.php

<?php ... // can call $pdo fine in file outside of functions ...  function authenticate($u, $p) {     // can't call $pdo in here, error says $pdo non-object     $que = $pdo->query('select user_id, user_pass users user_name = \'' . $u . '\' limit 1');     ... }  ?> 

by way, i'm using pdo because having similar trouble mysqli, , trying away mysql, apparently depreciated , discouraged.

edit: should have clarified first based on number of responses got on matter: did try pass $pdo in param function, no luck or change in error message.

solution: ok, apparently problem needed add require_once('config.php') in process.php file well. not sure why (wouldn't included when index.php run first?). able pass $pdo in param function, , voila.

that's pretty basic php stuff. variables inside functions local variables unless use global keyword load them. suppose want this:

function authenticate(pdo $pdo, $u, $p) {     $que = $pdo->query('select user_id, user_pass users user_name = \'' . $u . '\' limit 1');     //... } 

edit: if php claims $pdo not object, it's not object, doesn't matter how it's passed function. inspect variable right before call authenticate():

var_dump($pdo); 

without relevant code there's no way why. (assuming it's true new pdo succeeds.)


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -