尝试使用PDO对象时出错

时间:2012-07-05 15:09:22

标签: php mysql pdo

我是一名经验不足的php程序员,几天前才发现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();
    }
}

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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

答案 2 :(得分:0)

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

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