我试图用我所有的产品回应产品清单, 但我在mysql中有3个产品。但是由于某些原因,当我回复我的列表时,它只显示了一个产品,第一个列表。虽然我想看到所有的产品(3)。
如果这可能与我正在使用相关: 服务器版本:5.5.36 - MySQL 和[PHP:5.4.27]
// This block grabs the whole list for viewing
include "../sitescripts/connect_to_mysql.php";
$product_list = "";
$sql = mysql_query("SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list = "Product ID: $id - <strong>$product_name</strong> - $$price - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
答案 0 :(得分:2)
您的商品列表仅显示您行中的最后一项。
$product_list = "Product ID: $id - <strong>$product_name</strong> - $$price - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
正在覆盖每次迭代的值,我认为你打算这样做:
$product_list .= "Product ID: $id - <strong>$product_name</strong> - $$price - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
用于在每次迭代时附加字符串值。请注意=
符号前的句号。
答案 1 :(得分:1)
注意:
$product_list
变量 INSIDE
ELSE 条件。 NOT AFTER 条件。仅拥有最后一行的原因是因为最后一行行将覆盖循环的前一行。如果您将代码转换为 MySQLi ,它将如下所示:
<强> connect_to_mysql.php 强>:
<?php
/* ESTABLISH CONNECTION */
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase"); /* REPLACE NECESSARY DATA */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
您的抓取/主文件:
include "../sitescripts/connect_to_mysql.php"; /* INCLUDE CONNECTION */
$product_list = "";
$sql = mysqli_query($con,"SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
/* USED mysqli_real_escape_string FUNCTION TO PREVENT SQL INJECTION */
$id = mysqli_real_escape_string($con,$row["id"]);
$product_name = mysqli_real_escape_string($con,$row["product_name"]);
$price = mysqli_real_escape_string($con,$row["price"]);
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list = "Product ID: ".$id." - <strong>".$product_name."</strong> - $".$price." - <em>Added ".$date_added."</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
echo $product_list; /* PRINT $product_list VARIABLE */
} /* END OF WHILE LOOP */
} /* END OF $productCount VARIABLE IS MORE THAN 0 */
else {
$product_list = "You have no products listed in your store yet";
echo $product_list; /* PRINT $product_list VARIABLE */
} /* END OF ELSE */
/* I ASSUME YOU TRY TO PRINT THE $product_list VARIABLE IN HERE */