Databases Reference
In-Depth Information
// message
$message = "This user exists, but the password is incorrect. ".
" Choose another username, or fix the password.";
header("Location: index.php?message=" . urlencode($message));
exit;
}
}
We can be pretty certain that we'll get only a single match when we search for the user
and password pair, since username is the primary key of the users table. However, we
add an extra check to count the number of rows retrieved; if we get more than one,
something odd has happened, and we stop processing. This is an example of defensive
programming—thinking through all the possibilities that can occur and trying to en-
sure that your code can handle problems gracefully. The more effort you put into in-
serting checks into your code, the easier it will be to identify problems before they cause
irretrievable damage to your data or your relationship with your customers!
Incidentally, you could rewrite these three lines:
$matchedrows=0;
while($row = @ mysqli_fetch_array($result))
$matchedrows++;
in a for loop with an empty body (but note the semicolon at the end):
for($matchedrows=0; ($row = @ mysqli_fetch_array($result)) ; $matchedrows++);
In this loop, $matchedrows is initialized to 0 , and the loop is repeated as long as the
condition:
($row = @ mysqli_fetch_array($result))
is true (not zero). This will be the case as long as mysqli_fetch_array( ) finds another
row to fetch from the results. Each time the loop iterates, the value of matchedrows is
incremented by one. This code is more compact, but is also slightly harder to under-
stand. Try to avoid writing code that's too difficult to understand, and always add clear
comments to explain what the code is doing. It's very hard to understand badly com-
mented code, even if you wrote the code yourself.
Starting the User Session
After inserting a new username and password pair into the users table, or after verifying
that the provided username and password pair is correct, we know that the user is
authorized to access the system. We start a new session with the session_start( )
function and store the username in a session variable. We then redirect the browser to
the gift list page with a welcome message:
// Everything went OK. Start a session, store the username in a session variable,
// and redirect the browser to the gift list page with a welcome message.
session_start();
$_SESSION['username']=$username;
$message = "Welcome {$_SESSION['username']}! ".
 
Search WWH ::




Custom Search