0

Can anyone help me with a problem in portfolio? I have the webpage completed and presenting all stocks in someones portfolio, but it prints each stock 5 times instead of just one. Below I have the code from index.php. It will be great if anyone can point out which part of my code creates this problem. Thanks

// configuration
require("../includes/config.php"); 

//First we look for the user id 
$rows= CS50::query("SELECT * FROM Portfolios WHERE id=?", $_SESSION["id"]);

// we create an array to store all the information
$positions=array(); 

//Iterate over the rows of the database
foreach($rows as $row){

    //using the lookup function
    $stock=lookup($row["symbol"]);

    //Check if the function works right and then add the information 
    if ($stock !== false){

     $positions=array(   
         "name"=>$stock["name"],
         "price"=>$stock["price"],
         "shares"=>$row["shares"],
         "symbol"=>$row["symbol"],
         "total"=>$row["shares"] * $stock["price"]
         );

    }
}
$users= CS50::query("SELECT * FROM users WHERE id=?", $_SESSION["id"]); 
$balance=$users[0]["cash"]; 

// render portfolio
render("portfolio.php", ["positions"=>$positions, "title"=>"Positions", "balance"=>$balance]); 
0
0

instead of using the array function, you could use []. using the following code:

$positions = array(   
    "name"=>$stock["name"],
    "price"=>$stock["price"],
    "shares"=>$row["shares"],
    "symbol"=>$row["symbol"],
    "total"=>$row["shares"] * $stock["price"]
);

you're not appending a new array to $positions. rather, you're assigning a new array to it. so when your program iterates over $positions in your view, it's gonna iterate 5 times because that's how many elements are in $positions.

check out Arrays to learn more about how you can append elements to an array in PHP!


as a side note, perhaps you shouldn't assume that the query function will always return at least one row. recall that it may also return FALSE in some cases, so you wanna make sure that's not the case not to run into problems.

1
  • Thank you Kareem! It worked!
    – dean.d
    Jun 4 '16 at 14:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .