Fatal error: Uncaught Error: Call to a member function fetch() on string

Fatal error: Uncaught Error: Call to a member function fetch() on string

无法解决错误。我收到两个不同的错误

  1. 致命错误:未捕获错误:调用字符串上的成员函数 fetch()
  2. 错误:调用字符串的成员函数 fetch()

代码:

if (isset($_POST["query"])) {
    $search = $_POST["query"];
    $query = $dbh->prepare("SELECT * FROM `tbl_product` WHERE `name` LIKE :search;");
    $query->bindValue(':search','%'.$search.'%');
    $query->execute();
} else {
    $query = "SELECT * FROM tbl_product ORDER BY id";
}

//if($query->rowCount() > 0) ---- this also doesn't work
if($query) {
    while($row = $query->fetch(PDO::FETCH_ASSOC)) {
        $output .= 'TEST';
    }
    echo $output;
} else {
    echo 'Data Not Found';
}

这可能很像:

if (isset($_POST["query"])) {
    $search = $_POST["query"];
    $query = $dbh->prepare("SELECT * FROM `tbl_product` WHERE `name` LIKE :search;");
    $query->bindValue(':search','%'.$search.'%');

} else {
    /* not overwriting variable $query with a SQL string in here: */
    $query = $dbh->prepare("SELECT * FROM tbl_product ORDER BY id;"); "";
}
$query->execute();