尝试在循环准备语句结果时获取非对象的属性

问题描述 投票:1回答:2

我是PHP的新手,我试图执行此函数来从我的数据库表中选择行数,但我不明白为什么我得到这个错误

注意:尝试在322行的/Applications/XAMPP/xamppfiles/htdocs/Twitter/security/access.php中获取非对象的属性

第322行循环结果

 while ($row = $result->fetch_assoc()) {
            $returnArray[] = $row;
        }

这里是完整的代码,这里出了什么问题? :(

function selectPosts($id) {


        // declare array to store selected information
        $returnArray = array();

        // sql JOIN
        $sql = "SELECT posts.id,
        posts.uuid,
        posts.text,
        posts.path,
        posts.date,
        users.id,
        users.username,
        users.fullname,
        users.email,
        users.ava
        FROM Twitter.posts JOIN Twitter.users ON
        posts.id = $id AND users.id = $id ORDER by date DESC";

        // prepare to be executed
        $statement = $this->conn->prepare($sql);

        // error ocured
        if (!$statement) {
            throw new Exception($statement->error);
        }

        // execute sql
        $statement->execute();

        // result we got in execution
        $result = $statement->get_result();

        // each time append to $returnArray new row one by one when it is found
        while ($row = $result->fetch_assoc()) {
            $returnArray[] = $row;
        }

        return $returnArray;

    }
php
2个回答
1
投票

您的语句无法执行/失败,因此$result对象不可用。您可以使用以下内容确保获得结果:

function selectPosts($id) {

    // declare array to store selected information
    $returnArray = array();

    // sql JOIN
    $sql = "SELECT posts.id,
    posts.uuid,
    posts.text,
    posts.path,
    posts.date,
    users.id,
    users.username,
    users.fullname,
    users.email,
    users.ava
    FROM Twitter.posts JOIN Twitter.users ON
    posts.id = ? AND users.id = ? ORDER by date DESC";

    // prepare to be executed
    $statement = $this->conn->prepare($sql);
    $statement->bind_param('ii', $id, $id);

    // error ocured
    if (!$statement) {
        throw new Exception($statement->error);
    }

    // execute sql
    if (!$statement->execute()) {
        //execute fails
    }

    // result we got in execution
    $result = $statement->get_result();

    if ($result === false && ($statement->errno > 0 || $this->conn->errno)) {
        //result not available
    }

    // each time append to $returnArray new row one by one when it is found
    while ($row = $result->fetch_assoc()) {
        $returnArray[] = $row;
    }

    return $returnArray;

}

确保使用准备好的语句。


0
投票

您尝试从刚刚检查过的语句中获取错误是错误的。在这种情况下,您需要从连接中获取错误..而不是

if (!$statement) {
    throw new Exception($statement->error);
}

你需要...

if (!$statement) {
    throw new Exception($this->conn->error);
}

您还应该检查执行时是否有效...

if ( !$statement->execute() ) {
    throw new Exception($statement->error);
}
© www.soinside.com 2019 - 2024. All rights reserved.