【问题标题】:Looping through (and displaying) multiple table rows from SQL从 SQL 循环遍历(并显示)多个表行
【发布时间】:2012-01-18 01:40:30
【问题描述】:

无法循环遍历 SQL 表中的多行并正确显示信息。我得到的最接近的是:

<table border="1" cellpadding="10">
<th>Stock</th><th>Price</th><th>Shares</th><th>Value</th><th>Sell Stock</th>
<?php
$transactions = mysql_query("SELECT * FROM transactions WHERE email='$email'");
while ($rows = mysql_fetch_assoc($transactions)) {
    foreach($rows as $row) {
        $symbol = $row["symbol"];
        $price = $row["price"];
        $shares = $row["shares"];
        $value = $price * $shares;
?>
        <form name="sellStock" action="sell.php" method="get">
        <tr>
            <td><input name="symbol" type="hidden" value="<?php echo $symbol ?>"><?php echo $symbol ?></td>
            <td><input name="price" type="hidden" value="<?php echo $price ?>"><?php echo $price ?></td>
            <td><input name="shares" type="hidden" value="<?php echo $shares ?>"><?php echo $shares ?></td>
            <td><input name="value" type="hidden" value="<?php $value ?>" /><?php $value ?></td>
            <td><input name="sell" type="submit" value="Sell"></td>
        </tr>
<?php
    }
}
?>
</table>

while/foreach 循环继续将行中的信息显示到 HTML 表中,但它显示每列的第一个字符,而不是我回显要显示的列中的所有字符(符号、价格、和股份)。有什么想法吗?

【问题讨论】:

  • 你的意思是你这样做(例如)echo $symbol; 并且它只显示第一个字符?我们可能需要查看您编写的用于打印 HTML 表格的代码 - 如果可能的话,仍然会重现问题。
  • 你能把代码显示在它实际回显到表中的位置吗?
  • 是的,您的代码看起来不错。问题一定出在影响$symbol等的后续代码或其输出。

标签: php mysql sql phpmyadmin


【解决方案1】:
<table border="1" cellpadding="10">

<th>Stock</th><th>Price</th><th>Shares</th><th>Value</th><th>Sell Stock</th>
<?php
$transactions = mysql_query("SELECT * FROM transactions WHERE email='$email'");
while ($row = mysql_fetch_assoc($transactions)) {
        $symbol = $row["symbol"];
        $price = $row["price"];
        $shares = $row["shares"];
        $value = $price * $shares;
?>
        <form name="sellStock" action="sell.php" method="get">
        <tr>
            <td><input name="symbol" type="hidden" value="<?php echo $symbol ?>"><?php echo $symbol ?></td>
            <td><input name="price" type="hidden" value="<?php echo $price ?>"><?php echo $price ?></td>
            <td><input name="shares" type="hidden" value="<?php echo $shares ?>"><?php echo $shares ?></td>
            <td><input name="value" type="hidden" value="<?php $value ?>" /><?php $value ?></td>
            <td><input name="sell" type="submit" value="Sell"></td>
        </tr>
<?php
}
?>
</table>

你只是有一个循环太多。 while 循环一直持续到 !$row,每次执行一行,因此您不想要 foreach 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2018-12-06
    • 2014-02-16
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多