让我解释一下。我有一个简单的查询,当我在phpmyadmin上测试时,它可以工作,但它不会在我的Web应用程序中返回正确的答案。
这是运行查询的函数:
function GetProductsFromCategoryId($categoryId)
{
global $db;
$query = '
SELECT *
FROM `products`
WHERE categoryID = 3';
try {
$statement = $db->prepare($query);
//$statement->bindValue(':categoryId', $categoryId);
$statement->execute();
$result = $statement->fetch();
$statement->closeCursor();
return $result;
} catch (PDOException $e) {
$error_message = $e->getMessage();
display_db_error($error_message);
}
}
通常是categoryID = $ categoryID,但我用“3”硬编码,因为我想查看结果。还有整个其他数据库文件处理连接,我可以发布它们,如果你想,但其他功能工作正常。这是我在Murach的php book ch 24中使用的模板。这个函数是我自己的,略有修改。
使用SELECT *,该函数应为每个产品返回2个数组,稍后当我从phpmyadmin发布结果时您会看到。相反,它只为一个产品返回1个数组。
这是我在phpmyadmin中运行的查询:
SELECT * FROM `products` WHERE categoryID=3;
结果是:
9 3 ludwig Ludwig 5-piece Drum Set with Cymbals This product includes a Ludwig 5-piece drum set an... 699.99 30.00 2010-07-30 12:46:40
10 3 tama Tama 5-Piece Drum Set with Cymbals The Tama 5-piece Drum Set is the most affordable T... 799.99 15.00 2010-07-30 13:14:15
所以,正如你所看到的,它应该返回2个数组,因为fetch()函数应该这样做,但它只返回一个数组。我有xdebug设置netbeans并查看变量$ result,它有1个数组,其中productName为“Ludwig 5-piece ...”
我被困在这3天了,我不知道为什么它不起作用。请帮忙!
感谢!!!
PS:这是数据库表上的产品
1 1 strat Fender Stratocaster The Fender Stratocaster is the electric guitar des... 699.00 30.00 2009-10-30 09:32:40
2 1 les_paul Gibson Les Paul This Les Paul guitar offers a carved top and humbu... 1199.00 30.00 2009-12-05 16:33:13
3 1 sg Gibson SG This Gibson SG electric guitar takes the best of t... 2517.00 52.00 2010-02-04 11:04:31
4 1 fg700s Yamaha FG700S The Yamaha FG700S solid top acoustic guitar has th... 489.99 38.00 2010-06-01 11:12:59
5 1 washburn Washburn D10S The Washburn D10S acoustic guitar is superbly craf... 299.00 0.00 2010-07-30 13:58:35
6 1 rodriguez Rodriguez Caballero 11 Featuring a carefully chosen, solid Canadian cedar... 415.00 39.00 2010-07-30 14:12:41
7 2 precision Fender Precision The Fender Precision bass guitar delivers the soun... 799.99 30.00 2010-06-01 11:29:35
8 2 hofner Hofner Icon With authentic details inspired by the original, t... 499.99 25.00 2010-07-30 14:18:33
9 3 ludwig Ludwig 5-piece Drum Set with Cymbals This product includes a Ludwig 5-piece drum set an... 699.99 30.00 2010-07-30 12:46:40
10 3 tama Tama 5-Piece Drum Set with Cymbals The Tama 5-piece Drum Set is the most affordable T... 799.99 15.00 2010-07-30 13:14:15
第一列是productID,第二列是categoryID。
答案 0 :(得分:10)
您的$statement->fetch()
只返回数据库中的一行。见PDOStatement::fetch()
。我想您希望PDOStatement::fetchAll()
返回查询中的所有行。
答案 1 :(得分:7)
PDOStatement :: fetch()一次只返回一行。您必须迭代调用它以获取剩余的行。