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.

4
  • 1
    Well, first of all you should ensure that your connection.php is really included - maybe it's in another directory than class.php? Commented Aug 15, 2012 at 14:47
  • 2
    replace include with require,check if you are getting fatal error Commented Aug 15, 2012 at 14:48
  • YEs sir because if its not, there will be an error failed to open stream etc.. ^^ Commented Aug 15, 2012 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. That might tell you if the object is failing to be created properly. Commented Aug 15, 2012 at 14:54

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Read the answer on one of your links: stackoverflow.com/questions/4675932/… the answerer describes the global requirement for variable within inclusion functions
@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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.