PHP MySQL警告:非法字符串偏移'标题'

时间:2018-03-11 10:30:34

标签: php mysql string

我收到此错误:
警告:非法字符串偏移'标题'在第33行的C:\ wamp64 \ www \ Beep \ php \ config.php

使用此功能时:

function getComments() {
global $pdo;

$sql = "SELECT * FROM `comments`";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$results = $stmt->fetch();

$comments = array();
foreach ($results as $result) {
    array_push($comments, new Comment($result["title"], $result["content"], $result["author"]));
}
return $comments;}

class Comment {

    var $title;
    var $content;
    var $author;

    /**
     * Comment constructor.
     * @param $title
     * @param $content
     * @param $author
     */
    public function __construct($title, $content, $author){
        $this->title = $title;
        $this->content = $content;
        $this->author = $author;
    }
}

第33行是

array_push($comments, new Comment($result["title"], $result["content"], $result["author"]));

1 个答案:

答案 0 :(得分:0)

fetch()返回单个记录。当你foreach()超过结果时,你会迭代行的值,而不是行。

使用fetchAll()获取所有记录。

$results = $stmt->fetchAll();
foreach ($results as $result) {
    echo $result['title'];
}

在您的初始代码中:

$results = $stmt->fetch();
foreach ($results as $result) {
    echo $result; // here $result is id, then title, and so on.
}