1

ok trying to start pset7, need help understanding login.php

here is the part I want to undertand

if (count($rows) == 1)
    {
        // first (and only) row
        $row = $rows[0];

        // compare hash of user's input against hash that's in database
        if (password_verify($_POST["password"], $row["hash"]))
        {
            // remember that user's now logged in by storing user's ID in session
            $_SESSION["id"] = $row["id"];

            // redirect to portfolio
            redirect("/");
        }
    }
  1. Just wanna know does this if(count($rows) == 1 mean the query returns true or false? I mean if it returned something (a user name exsist) than 1 otherwise 0?

  2. why are we initializing $row = $row[0]? what if there were two same usernames? We wont be able to check the second one.... and if there were only one such username than still why the need to initialize it to 0? or did I understood something wrong?

  3. How would this redirect("/"); redirect to portfolio?

1 Answer 1

0
  1. Just wanna know does this if(count($rows) == 1 mean the query returns true or false? I mean if it returned something (a user name exsist) than 1 otherwise 0?

count($rows) does what it sounds like it is doing : it counts the number of rows returned by the query. If that number equals 1, this conditional expression evaluates to true.

It's worth noting that, if you have set things up correctly, the number of rows returned should never be greater than 1.

  1. why are we initializing $row = $row[0]? what if there were two same usernames? We wont be able to check the second one.... and if there were only one such username than still why the need to initialize it to 0? or did I understood something wrong?

You can't have two users with the same username in your database. Think about it -- how would you be able to tell them apart?

More importantly, you are not setting $row = $row[0]. What you are actually doing is:

$row = $rows[0]

The CS50::query() does not just return a row of data; it returns an array of rows. In this case, it is only returning one row, but it will still return that row as an array with only one element. To index directly into the values in the first element of the $rows array, we can do this:

$rows[0]["id"]

Or, to make it a bit simpler, we can assign $row = $rows[0] and then just:

$row["id"]

This is a fine point, but one that can trip you up if you're not careful.

  1. How would this redirect("/"); redirect to portfolio?

It redirects to / which is the Apache2 server's root directory. There it finds and executes index.php, which should render a different View if the user is logged in.

You must log in to answer this question.

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