如何使用PHP从MySql查询中显示多个结果

时间:2014-03-10 22:53:17

标签: php html mysql

我的当前代码工作正常,但是当我希望代码显示在名为wine的表中存在多个查询时,我需要帮助...例如,如果类别中的葡萄酒类型不仅仅是西班牙那么它应该显示全部,但只显示一个。

这是我的PHP:

<?php  

include"db_connection.php";

$sql = mysql_query("SELECT * FROM WINE WHERE country='Chile'");
    while($row = mysql_fetch_array($sql)){ 
         $description = $row["description"];
         $wine_type = $row["wine_type"];
         $country = $row["country"];
         $bottle_price = $row["bottle_price"];
         $indicator = $row["indicator"];
         $colour = $row["colour"];
         $case_price = $row["case_price"];
         $case_size = $row["case_size"];         
         $date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));    
     }
?>

这是我的HTML:

<?php include('header.php'); ?>

<div id="content">
<table width="100%" border="0" cellspacing="0" cellpadding="15">
    <tr>
        <td width="19%" valign="top"><img src="inventory_images/<?php echo $id; ?>.jpg" width="142" height="188" alt="<?php echo $wine_type; ?>" /><br />
        <a href="inventory_images/<?php echo $id; ?>.jpg">View Full Size Image</a></td>
            <td width="81%" valign="top"><h3><?php echo $wine_type; ?></h3>
            <p><?php echo "$".$bottle_price; ?><br /><br />
                <?php echo "$country $indicator"; ?> <br /><br />
                <?php echo $description; ?> <br />
            </p>

              <form id="form1" name="form1" method="post" action="cart.php">
                <input type="hidden" name="pid" id="pid" value="<?php echo $id; ?>" />
                <input type="submit" name="button" id="button" value="Add to Shopping Cart" />
              </form>
            </td>
    </tr>
</table>
</div>

<?php include('footer.php'); ?>

1 个答案:

答案 0 :(得分:2)

目前的问题是while()循环将继续覆盖变量。这可以通过几种方式解决,一种方法是将整个获取的列保存在一个数组中,然后再使用该数组进行迭代。

$allRows = array();
while($row = mysql_fetch_array($sql)) {
    $allRows[] = $row;
}

现在,如上所述,在模板中迭代$allRows

<?php include('header.php'); ?>
<div id="content">
<table width="100%" border="0" cellspacing="0" cellpadding="15">
<?php
foreach ($allRows as $row) {
?>
    <tr>
      <td width="19%" valign="top"><img src="inventory_images/<?php echo $row['id']; ?>.jpg" width="142" height="188" alt="<?php echo $row['wine_type']; ?>" /><br />
      etc.
    </tr>
<?php
}
?>
</table>
</div>
<?php include('footer.php'); ?>

在这里,我将变量称为$row['...'] - 如果您不想更改代码的那一部分,只需在循环开始时进行分配。

etc.
<?php
foreach ($allRows as $row) {
     $description = $row["description"];
     $wine_type = $row["wine_type"];
     //etc.
?>

一个更清晰的解决方案(不混合那些通常会产生很多混淆的HTML和PHP)将使用模板引擎。也不要在新代码中使用mysql_*函数 - 它们是deprecated。有关详细信息,请参阅this answer

相关问题