我正在使用PDO并将我的查询放入try块,我准备它,然后调用execute on it,接下来fetchAll(PDO::FETCH_ASSOC)
就可以了。在行中我需要文本我将PHP放在foreach循环中,$tools
变量为$obj
。然后我想到了#34;我正在调用我在代码中添加变量$obj
,并引用了来自mySQL的' name',' price'和' code'。
只是吐出查询字符串的错误
object(PDOStatement)#2(1){["queryString"]}=>...the Sql statmement.
try {
$tools = $dbh->prepare("SELECT t.item_code as code, t.item_name as
name, t.retail_price as retail,
t.sale_price as price, t.item_pieces as
pieces, t.qty as quantity,
t.sold as sold, b.brand as brand,
c.category as category
FROM Tools AS t
JOIN Images AS i ON t.t_id = i.t_id
JOIN Brands AS b ON t.b_id = b.b_id
JOIN Categories AS c ON t.c_id =
c.c_id
LEFT OUTER JOIN Types as tt ON tt.t_id = t.tt_id");
$tools->execute();
$tools->fetchAll(PDO::FETCH_ASSOC);
}catch (PDOException $e) {
echo 'unable to retrieve data';
echo $e->getMessage();
exit();
}
<?php
foreach($tools as $obj) {
?>
<div class="col-xs-12 col-sm-6 col-md-3">
<article class="card">
<p class="text-center">
Item: <?php echo $obj->name; ?><br>
Brand: <br>
Price: <?php echo $obj->price; ?><br>
<button class="btn btn-default btn-lg"
value="<?php echo $obj->name; ?>">
<a href="#"><?php echo $obj->code;
?></a>
</button>
</p>
</article>
</div>
<?php } ?>
带有网页的代码消息。
`object(PDOStatement)#2 (1) { ["queryString"]=> string(609) "SELECT t.item_code as code, t.item_name as name, t.retail_price as retail, t.sale_price as price, t.item_pieces as pieces, t.qty as quantity, t.sold as sold, b.brand as brand, c.category as category FROM Tools AS t JOIN Images AS i ON t.t_id = i.t_id JOIN Brands AS b ON t.b_id = b.b_id JOIN Categories AS c ON t.c_id = c.c_id LEFT OUTER JOIN Types as tt ON tt.t_id = t.tt_id" }`
答案 0 :(得分:1)
$tools->fetchAll(PDO::FETCH_ASSOC);
是个问题。 fetchAll
从语句中获取所有行并返回它们。如果您要使用它,则需要将该表达式的结果分配给另一个变量,例如:
$results = $tools->fetchAll(PDO::FETCH_ASSOC);
然后您可以foreach($results...
代替foreach($tools...
或者,您应该可以删除fetchAll
表达式。 PDOStatement实现了可遍历,并且可以在执行后直接使用foreach进行迭代,而无需使用fetch方法。