我收到错误声明:
在第16行的/home/content/26/11794426/html/practice/home.php中调用非对象的成员函数fetch()
基于此,我相信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();
}
?>
答案 0 :(得分:0)
$category = $db->query($query);
$categorys = $category->fetch();
$category_name = $categorys['categoryName'];
答案 1 :(得分:0)
您可以使用fetch_assoc();
进行尝试$query = "SELECT * FROM categories
WHERE categoryID = $category_id";
$category = $db->query($query);
$category = $category->fetch_assoc();
$category_name = $category['categoryName'];
但问题是数据库连接。在哪里定义?
答案 2 :(得分:0)
尝试调试您的代码,并添加此添加此代码
// Get name for current category
$query = "SELECT * FROM categories
WHERE categoryID = $category_id";
$category = $db->query($query);
echo mysql_nun_rows($category);
$categories = $category->fetch();
$category_name = $categories['categoryName'];
如果发现仍有错误,请检查数据库连接