1

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

我得到的错误是:

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

代码如下所示:

索引.php

class myClass
{
        ... variables ...

        ... functions ...

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

            require('file1.php');

            ... stuff ...
        }
}

文件1.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 ...

文件2.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();
    }
}
4

3 回答 3

1

如果我理解您的逻辑正确,您正在尝试使用 myFunction2 中的 PDO 对象 - 您是将 PDO 对象作为参数传递,还是将其声明为全局变量?因为如果您不这样做,它将超出范围,您将无法使用它。

于 2012-07-05T15:19:35.713 回答
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
于 2012-07-05T15:14:23.147 回答
0

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

$pdo = new PDO("dsn");
/* Some code... at the moment something changes $pdo value */
$pdo->prepare("QUERY");
于 2012-07-05T15:14:30.093 回答