我收到错误声明:
Call to a member function fetch() on a non-object in /home/content/26/11794426/html/practice/home.php on line 16
基于此,我相信 mysql 查询没有创建对象。但是,我直接从书中复制代码,所以我很困惑为什么会出现错误。是 fetch() 部分本身还是查询?
另外,我将 sql 查询复制并粘贴到 phpmyadmin 的数据库中,所以我认为那里没有错误,但我不排除它。
有什么想法吗?
<?php
require_once('database.php');
// Get category ID
if(!isset($category_id)) {
$category_id = $_GET['category_id'];
if (!isset($category_id)) {
$category_id = 1;
}
}
// Get name for current category
$query = "SELECT * FROM categories
WHERE categoryID = $category_id";
$category = $db->query($query);
$category = $category->fetch();
$category_name = $category['categoryName'];
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$categories = $db->query($query);
// Get products for selected category
$query = "SELECT * FROM products
WHERE categoryID = $category_id
ORDER BY productID";
$products = $db->query($query);
?>
这就是我的database.php 文件的样子:
<?php
$dsn = 'mysql:host=guitarshop27.db.11794426.hostedresource.com;dbname = guitarshop27';
$username = 'changed';
$password = 'changed';
try {
$db = new PDO($dsn, $username, $password);
}catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
最佳答案
$category = $db->query($query);
$categorys = $category->fetch();
$category_name = $categorys['categoryName'];
关于php - fetch() 方法出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20164926/