0
//this is my connection.php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;', 'root');
$pdo->exec("SET CHARACTER SET utf8");
?>


//this is my class.php
<?php
include 'connection.php';
$stmt = $pdo->prepare(query here); //wrong part
?>

problem: Error undefined $pdo, what is the right way in doing this? But when i transfer the code from the connection.php to class.php it works fine.

j0k
  • 22,600
  • 28
  • 79
  • 90
Sui Go
  • 463
  • 2
  • 12
  • 31
  • 1
    Well, first of all you should ensure that your connection.php is really included - maybe it's in another directory than class.php? – RSeidelsohn Aug 15 '12 at 14:47
  • 2
    replace include with require,check if you are getting fatal error – Tarun Aug 15 '12 at 14:48
  • YEs sir because if its not, there will be an error failed to open stream etc.. ^^ – Sui Go Aug 15 '12 at 14:49
  • Try wrapping your PDO object construction in a `try {} catch()` block, as shown in example 2 on this page: [Connections and Connection management](http://www.php.net/manual/en/pdo.connections.php). That might tell you if the object is failing to be created properly. – Jonah Bishop Aug 15 '12 at 14:54

1 Answers1

2

Declare the $pdo as global in the above file connection.php.

Check Passing a variable from one php include file to another: global vs. not and Passing variables in PHP from one file to another

Community
  • 1
  • 1
verisimilitude
  • 5,077
  • 3
  • 30
  • 35
  • I don't think this should be the case. If he were including connection.php and then in connection.php trying to use `$stmt` then it should be the case I believe. – Sammaye Aug 15 '12 at 14:57
  • Read the answer on one of your links: http://stackoverflow.com/questions/4675932/passing-a-variable-from-one-php-include-file-to-another-global-vs-not the answerer describes the global requirement for variable within inclusion functions – Sammaye Aug 15 '12 at 15:02
  • @Sammaye: I still did'nt get your point. But since this has now been accepted as an answer, i think this was what the OP was looking for. – verisimilitude Aug 15 '12 at 15:18
  • To quote a comment from the answerer: `So, the parent file has access to variables in both included files, but the included file doesn't have access to the other included file.` Indeed it worked because of the global scope of it, however according to PHP semantics from linked questions it shouldn't be the right answer. – Sammaye Aug 15 '12 at 15:21