mysql - My php loop is looping 11 times, instead of one. Cant find the bug -
here php code. functions require, query , render given us.
<?php // configuration require("../includes/config.php"); $rows = cs50::query("select `symbol`, `shares`, `cash` `portfolios`, `users` ?", $_session["id"]); $positions = []; foreach ($rows $row) { $stock = lookup($row["symbol"]); $total = ($stock["price"] * $row["shares"]); if ($stock !== false) { $positions[] = [ "name" => $stock["name"], "price" => $stock["price"], "shares" => $row["shares"], "symbol" => $row["symbol"], "total" => $total, "cash" => $row["cash"] ]; } } // render portfolio render("portfolio.php", ["positions" => $positions, "title" => "portfolio"]);
here html output
<div id="middle"> <table class="table table-striped"> <thead> <tr> <th >symbol</th> <th >name</th> <th >shares</th> <th >price</th> <th >total</th> </tr> </thead> <tbody> <?php foreach ($positions $position): ?> <tr> <td align="left" ><?= $position["symbol"] ?></td> <td align="left" ><?= $position["name"] ?></td> <td align="left" ><?= $position["shares"] ?></td> <td align="left" ><?= number_format($position["price"], 2) ?></td> <td align="left" ><?= number_format($position["total"], 2) ?></td> </tr> <?php endforeach ?> <tr> <td colspan="4" align="left">cash</td> <td align="left"><?= number_format($position["cash"], 2) ?></td> </tr> </tbody> </table>
my guess there wrong foreach loop. im not quite sure, there faults in sql database.
my mysql database consist of 3 rows user_id
, symbol
, shares
. , user_id have 3 diffrent stocks 10 shares each.
anyone know wrong?
if runs 7 times means there 7 rows returned, foreach loop fine. issue here:
$rows = cs50::query("select `symbol`, `shares`, `cash` `portfolios`, `users` ?", $_session["id"]);
you aren't indicating column should equal id, it's returning of them likely. need this:
$rows = cs50::query("select `symbol`, `shares`, `cash` `portfolios`, `users` portfolios.user_id = ?", $_session["id"]);
Comments
Post a Comment