0

i have config file that contain a function that connects to database on my server and here is the code

config file

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

define('USER', 'root');
define('PASS', '');

function communicate($dbname){

 try {
 $dbh = new PDO('mysql:host=serverip;dbname='.$dbname.'', USER, PASS);
 $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
 $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


    }
    catch(PDOException $e) {
        echo $e->getMessage();
        $errorCode = $e->getCode();
    }



}
?>

other page to do some stuff

require('dbs/connfile.php');



if (isset($_GET['id'])) {

$accountname = 'dbname';
communicate($accountname);


$query = "SELECT * FROM datatbl"; 
$result= $dbh->prepare($query);
$result->execute();
while ($row = $result->fetch()) {       
$cmail = $row['email'];
}

}

i got and error that said

Notice: Undefined variable: dbh in /home/moudlepath/page.php

and thats because $dbh isn't global how can i use that connection file in any page that included into it ?

Vlark.Lopin
  • 762
  • 10
  • 21
  • Since $dbh is created within the `communicate` method, it is scoped to that method. Best bet is just make `communicate` return the $dbh, then set dbh with communicates output. – Carl Sep 26 '16 at 20:11

1 Answers1

1

Simple solution is:

function communicate($dbname){

     try {
         $dbh = new PDO('mysql:host=serverip;dbname='.$dbname.'', USER, PASS);
         $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
         $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e) {
        echo $e->getMessage();
        $errorCode = $e->getCode();
    }

    return $dbh;  // see this? return your $dbh
}

And usage:

$dbh = communicate($accountname);
u_mulder
  • 54,101
  • 5
  • 48
  • 64