我是一個沒有經驗的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();
}
}
我們需要看代碼,但是我敢打賭,如果PDO對象是在'method myfunction()'內部定義的,那麼你正在使用的函數中的PDO對象超出了範圍。 – 2012-07-05 15:11:18
您應該將錯誤還有一些關聯代碼和連接細節已經被清除了。 – 2012-07-05 15:11:23
你能告訴我們代碼,而不是描述它嗎? – 2012-07-05 15:11:39