我是php的新手,也是发布php代码的新手。因此,如果缺少任何信息,请告诉我。我正在尝试让产品列表通过 foreach 循环回显。我不确定错误是否只是语法或比这更大的错误。以下是错误消息:
Home
Product List
Code Name Version Release Date
( ! ) Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/tech_support/product_manager/product_list.php on line 15
Call Stack
# Time Memory Function Location
1 0.0004 247496 {main}( ) ../index.php:0
2 0.0024 273008 include( '/Applications/XAMPP/xamppfiles/htdocs/tech_support/product_manager/product_list.php' ) ../index.php:20
这是product_list php。
<?php include '../view/header.php'; ?>
<h1>Product List</h1>
<!-- display a table of products -->
<h2><?php echo $products; ?></h2>
<tr>
<th>Code</th>
<th>Name</th>
<th>Version</th>
<th>Release Date</th>
<th> </th>
</tr>
<?php foreach ($products as $product) : ?> //<-----line 15
<tr>
<td><?php echo $product['product_id']; ?></td>
<td><?php echo $product['name']; ?></td>
<td class="right"><?php echo $product['version']; ?></td>
<td><form action="." method="post">
<input type="hidden" name="product_id"
value="<?php echo $product['releaseDate']; ?>">
<input type="submit" value="Delete">
</form></td>
</tr>
<?php endforeach; ?>
<p><a href="?action=show_add_form">Add Product</a></p>
<?php include '../view/footer.php'; ?>
这是我在索引文件夹中的代码。
<?php
require('../model/database.php');
require('../model/product_db.php');
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = filter_input(INPUT_GET, 'action');
if ($action === NULL) {
$action = 'list_products';
}
}
if ($action == 'list_products') {
$product_id = filter_input(INPUT_GET, 'product_id',
FILTER_VALIDATE_INT);
if ($product_id == NULL || $product_id == FALSE) {
$product_id = 1;
}
$products = get_product($product_id);
include('product_list.php');
}
else if ($action == 'show_add_form') {
$product = get_product($product_id);
include('product_add.php');
.......
以防万一这是我的数据库函数
<?php
function get_product($product_id) {
global $db;
$query = 'SELECT * FROM products
WHERE productCode = :product_id';
$statement = $db->prepare($query);
$statement->bindValue(":product_id", $product_id);
$statement->execute();
$products = $statement->fetch();
$statement->closeCursor();
return $products;
}
?>
如果$products
是一个对象,你可以在循环使用它之前尝试对其进行类型转换,如下所示:
$array = (array) $yourObject;
作为研究:
PDO获取
它返回一个数据数组,而不是预期的对象。
所以,尝试
var_dump( $products );
看看它到底是什么...对象或数组。
希望有帮助。