0

I encountered a problem while doing pset7. In portfolio.php, I would like to include not only the info of stocks a user own, but also his/her username and cash as well. So I wrote the following code, query both from the "users" table and "portfolios" table. But then I had this "undefined index" problem.

<?php

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

    if (isset($_SESSION["id"]))
    {
        //user info from table user
        $user = CS50::query("SELECT username, cash FROM users WHERE id = ?", $_SESSION["id"]);
        $user["cash"] = number_format($user["cash"], $decimals = 2, $dec_point = "." , $thousands_sep = "," );

         ..........
        //get info of stocks that a user owns using query()

        // render portfolio
        render("portfolio.php", ["title" => "Portfolio", "user" => $user["username"], "cash" => $user["cash"], "positions" => $positions]);
    }

    else
    {
        // else render form
        render("login_form.php", ["title" => "Log In"]);
    }

?>

This is my portfolio.php code:

<div>
    <?= "Username: " . $user . "     Cash Available: " . $cash?>

</div>

<div>
    <?php foreach ($positions as $position): ?>

        <tr>
            <td><?= $position["symbol"] ?></td>
            <td><?= $position["name"] ?></td>
            <td><?= $position["shares"] ?></td>
            <td><?= $position["price"] ?></td>
        </tr>
        <br/>

    <?php endforeach ?>
</div>

When I log in, the page looks like this: enter image description here

0

CS50::query() always returns an array of rows, even when the result is just one row.

For that reason, you should use [0] after user to be able to access the index ["cash"], like this:

$user[0]["cash"]

or reassign user like this:

$user = $user[0]

then you'll get to use $user["cash"] directly without the [0]


If you open the login.php file (which was written by the staff) and ctrl+F this, for example:

// first (and only) row
$row = $rows[0];

... you'll see that staff had to use $rows[0] to extract a $row from the array of rows.


If this is enough to solve your problem, please click the check mark to accept this answer and close it.

1

You must log in to answer this question.

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