Working within index.php, I feel like I understand the logic of what is going on, and I can get portfolio.php to render out fine on the website - with the exception that it only prints out one row from my portfolio table (title of table is "Stocks").
Here is index.php :
<?php
// configuration
require("../includes/config.php");
$rows = CS50::query("SELECT * FROM Stocks WHERE user_id = ?", $_SESSION["id"]);
$positions = [];
//iterate through rows
foreach ($rows as $row)
{
$stock = lookup($row["symbol"]);
if ($stock !== false)
{
$positions[] = [
"name" => $stock["name"],
"price" => $stock["price"],
"shares" => $row["share"],
"symbol" => $row["symbol"]
];
}
}
$cash = CS50::query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
//var_dump($portfolio);
// render portfolio
render("portfolio.php", ["title" => "Portfolio", "positions" => $positions,
"cash" => $cash]);
?>
<!--- Overhaul index.php (a controller) and portfolio.php (a view) in such a way that
they report each of the stocks in a user’s portfolio, including number of shares and
current price thereof, along with a user’s current cash balance. --->
Using dump / var_dump, I see that $rows is filling up fine with the following (given a test case):
Array
(
[0] => Array
(
[id] => 13
[user_id] => 11
[symbol] => AAPL
[share] => 11
)
[1] => Array
(
[id] => 15
[user_id] => 11
[symbol] => IDK
[share] => 3
)
)
dump() on $positions, however :
Array
(
[0] => Array
(
[name] => Apple Inc.
[price] => 108.84
[shares] => 11
[symbol] => AAPL
)
)
Why is this happening? Shouldn't the foreach() loop be giving $positions an additional index each time the loop iterates? My tables are set up such that logging in as user "hello" with a user id of "11" should reveal two rows within my "Stocks" table. Below are both tables.
"users" table:
I don't think portfolio.php has anything to do with this, but here it is:
<div>
<div>Here's your portfolio! Not yours? Then log out......</div>
<table>
<tr>
<th> Symbol </th>
<th> Name </th>
<th> Price </th>
<th> Shares </th>
</tr>
<?php foreach ($positions as $position): ?>
<tr>
<td><?= $position["symbol"] ?></td>
<td><?= $position["name"] ?></td>
<td><?= $position["price"] ?></td>
<td><?= $position["shares"] ?></td>
</tr>
<?php endforeach ?>
</table>
<table>
<tr>
<th> Cash Balance </th>
</tr>
<tr>
<td><?= $cash[0]["cash"] ?></td>
</tr>
</table>
</div>
Any help would be greatly appreciated.