Reputation: 81
Having trouble looping through multiple rows in a SQL table and getting the info to display correctly. The closest I have got is the following:
<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>
The while/foreach loop goes on to display the info from the rows into a HTML table, but it displays the first character from every column as opposed to all the characters from the columns I echo to be displayed (symbol, price, and shares). Any ideas?
Upvotes: 1
Views: 8353
Reputation: 98469
<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>
You just had one loop too many. The while
loop continues until !$row
, with one row per execution, so you don't want the foreach
loop you had.
Upvotes: 3