2012-07-05 121 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