I am doing index.php, and I have managed to display the table with all the data, but I can do that for only one row, i.e. if the user has only one type of stock. When I test the code for multiple rows, I get a whole gamut of mistakes, but I don't see why the code is incorrect. I am among less comfortable, and php seems more difficult than C to me. Please, take a look at the code that I have written for index.php to render the Portfolio. I will be grateful for your help! Per spec, CS50::query("SELECT....") returns the number of rows retrieved from the table. If I understand it correctly, I can't use mysqli_num_rows() function because to use it I have to use mysqli_query(), which is substituted by CS50::query function. http://www.w3schools.com/php/func_mysqli_num_rows.asp

//retrieve username and cash from table users
$rows_one = CS50::query("SELECT username, cash FROM users WHERE id = ?", $_SESSION["id"]);

//retrieve name, symbol, shares from portfolios table
$rows_two = CS50::query("SELECT Company_name, Symbol, Number_of_Shares FROM Portfolios WHERE Users_id = ?", $_SESSION["id"]);

$username = $rows_one[0]["username"];
$total_cash = $rows_one[0]["cash"];

//count how many rows were retrieved by CS50::query("SELECT...")
$row_count = count($rows_two);

    $positions = [];
    foreach ($rows_two as $row)
        $stock = lookup($rows_two[$row_count]["Symbol"]);
        if ($stock !== false)
           $positions[] = [
               "Company_name" => $stock["name"],
               "Stock_Symbol" => $rows_two[$row_count]["Symbol"],
               "Number_of_Shares" => $rows_two[$row_count]["Number_of_Shares"],
               "Price_per_share" => $stock["price"]

    // render portfolio
    render("portfolio.php", ["Username" => $username, "Total_cash" => $total_cash, "positions" => $positions, "title" => "Portfolio"]);

   //update row_count 

Thank you very much!

1 Answer 1


First, you should not have to count the rows. What you want to do is stick what you get from the second SQL query and lookup into that key value pair. That while loop is completely unnecessary and I would be willing to bet that that's what's giving you problems. Everything else looks pretty skookem.

Try ridding yourself of that while loop and other extraneous $row_count bits and you should be good to go!

  • Thank you very much for your answer. I have deleted my previous comments because I have found my error - I should have used $row and not $rows_two within the foreach loop. Solved )
    – Vitale
    Aug 2, 2016 at 8:15

You must log in to answer this question.

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