【问题标题】:Fatal error: Call to a member function prepare() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/connect/includes/functions.php [duplicate]致命错误:在 /Applications/XAMPP/xamppfiles/htdocs/connect/includes/functions.php 中的非对象上调用成员函数 prepare() [重复]
【发布时间】:2013-01-16 00:53:07
【问题描述】:

可能重复:
Scope error - Call to a member function prepare() on a non-object

我大约 2 或 3 个月前在我的 Windows PC 上编写了这段代码。它运行.. 现在我在我的 Mac 上下载了 xampp,我收到以下错误:

致命错误:在第 39 行的 /Applications/XAMPP/xamppfiles/htdocs/connect/includes/functions.php 中的非对象上调用成员函数 prepare()

// Connect to the database
    try {
        $pdo = new PDO('mysql:host=localhost;dbname=mo33', 'root', '');
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    }catch (PDOException $e){
        $error = "There was an issue connecting to the database: \n" + $e->getMessage();
        include 'html/error.html.php';
        exit();
    }

function renderTimeline(){

        try {
            $sql = 'SELECT user_publications.id, user.firstname, user.lastname, user.thumbnail, article, date_added
                    FROM user_publications INNER JOIN user 
            ON user_id = user.id 
            ORDER BY user_publications.id DESC';
            $s = $pdo->prepare($sql);   ---------------------------LINE 39--------------- 
            $result = $pdo->query($sql);
        }catch(PDOException $e){
            $output = 'There was an error while finding posts in the database..: ' . $e->getMessage();
            include 'html/error.html.php';
            exit();
        }

        while($row = $result->fetch()) {
            $user_publications[] = array(
        'id'=>$row['id'], 
        'name'=>$row['firstname'] + " " + $row['lastname'], 
        'thumbnail'=>$row['thumbnail'], 
        'article'=>$row['article'], 
        'date'=>$row['date_added']);
        }
        foreach ($user_publications as $post) {
            renderUserPublication($post['id'], $post['name'], $post['thumbnail'], $post['article'], $post['date']);
        }

        return;
    }

【问题讨论】:

  • renderTimeline 函数的作用域内没有 $pdo 变量。
  • 它需要在我创建的每个访问数据库的函数中吗?有没有更有效的方法?
  • 只需将 $pdo 传递给您的函数function renderTimeline($pdo) {...

标签: php sql object pdo


【解决方案1】:

将对象也传递给你的函数

function renderTimeline($pdo){

在你的代码中

$pdo = new pdo();
renderTimeline($pdo);

【讨论】:

    猜你喜欢
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多