2012-07-05 146 views
1

我是一个没有经验的php程序员,几天前才发现PDO。我现在试图将我的网站代码移植到使用PDO,但是当我尝试使用我创建的PDO对象时出现错误。尝试使用PDO对象时出错

我得到的错误是:

Fatal error: Call to a member function prepare() on a non-object in ... file2.php ... 

的代码看起来是这样的:

的index.php

class myClass 
{ 
     ... variables ... 

     ... functions ... 

     public function myFunction() // gets called on page load, outputs content to page 
     { 
      ... stuff ... 

      require('file1.php'); 

      ... stuff ... 
     } 
} 

file1.php

require_once('mysql_connect.php'); // create pdo object if not created 

... stuff ... 

require_once('file2.php'); 

// I can use the PDO object in here to make queries 

$output = function2(); // function2 is in file2.php 

... stuff ... 

file2.php

require_once('mysql_connect.php'); // create pdo object if not created 

function function2() 
{ 
    ... stuff ... 

    // PDO error occurs here 
    $stmt = $db->prepare(...); 
    makeQuery($stmt, array(...)); 

    return $something; 
} 

mysql_connect.php

try 
{ 
    $db = new PDO("mysql:$dbhost=localhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); 
} 
catch (PDOException $e) 
{ 
    print "Error!: " . $e->getMessage() . "<br/>"; 
    die(); 
} 

function makeQuery($stmt, $array = array()) 
{ 
    try 
    { 
     $stmt->execute($array); 
    } 
    catch (PDOException $e) 
    { 
     print "Error!: " . $e->getMessage() . "<br/>"; 
     die(); 
    } 
} 
+1

我们需要看代码,但是我敢打赌,如果PDO对象是在'method myfunction()'内部定义的,那么你正在使用的函数中的PDO对象超出了范围。 – 2012-07-05 15:11:18

+1

您应该将错误还有一些关联代码和连接细节已经被清除了。 – 2012-07-05 15:11:23

+1

你能告诉我们代码,而不是描述它吗? – 2012-07-05 15:11:39

回答

1

如果我理解你的逻辑正确,你正在尝试使用内myFunction2 PDO的对象 - 你传递PDO对象作为参数,或者它声明为一个全局变量?因为如果你不是,它会超出范围,你将无法使用它。

+0

我只是尝试在使用PDO对象的函数中添加'global $ db;',并且它没有改变任何东西。 – Nate 2012-07-05 16:02:43

+0

你可以尝试在函数内移动'include('mysql_connect.php')'调用吗? – andrewsi 2012-07-05 16:04:34

+0

嗯,我可以,但我不确定这是一个好主意,因为我有几百个需要查询的函数。所以看起来像包含一个文件并在每个函数内部创建一个新的$ db对象将是一种浪费。 – Nate 2012-07-05 16:07:41

0

您不必再包括mysql_coonect。 只包括一次。

index.php 
-class myClass defined 
--method myFunction defined (it get's called on pageload & returns the page output) 
---include file1.php 
----require_once('mysql_connect.php') (creates pdo object) 
----*I can use the pdo object here successfully* 
----require_once('file2.php') 
-----function myFunction2 defined 
0

DSN,用户名和密码是否正确?如果是这样,你做这样的事情:

$pdo = new PDO("dsn"); 
/* Some code... at the moment something changes $pdo value */ 
$pdo->prepare("QUERY"); 
+0

PDO在连接失败时抛出异常 - 事实上我们没有看到异常错误消息,告诉我OP成功连接并没有首先实例化PDO。 – DaveRandom 2012-07-05 15:15:33

+0

是的,我不太熟悉PDO。但绝对是PDO实例正在发生的事情。 – pamil 2012-07-05 15:23:47