13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Implementing User Authentication<br />

583<br />

Listing 27.9<br />

}<br />

Continued<br />

if ($result->num_rows>0) {<br />

throw new Exception('That username is taken - go back <strong>and</strong> choose another<br />

one.');<br />

}<br />

// if ok, put in db<br />

$result = $conn->query("insert into user values<br />

('".$username."', sha1('".$password."'), '".$email."')");<br />

if (!$result) {<br />

throw new Exception('Could not register you in database - please try again<br />

later.');<br />

}<br />

}<br />

return true;<br />

There is nothing particularly new in this function; it connects to the database you set up<br />

earlier. If the username selected is taken or the database cannot be updated, it will throw<br />

an exception. Otherwise, it will update the database <strong>and</strong> return true.<br />

Note that you are performing the actual database connection with a function called<br />

db_connect(), which we wrote.This function simply provides a single location that contains<br />

the username <strong>and</strong> password to connect to the database.That way, if you change the<br />

database password, you need to change only one file in the application.The db_connect()<br />

function is shown in Listing 27.10.<br />

Listing 27.10 db_connect()Function from db_fns.php—This Function Connects to<br />

the <strong>MySQL</strong> Database<br />

<br />

When users are registered, they can log in <strong>and</strong> out using the regular login <strong>and</strong> logout<br />

pages.You build them next.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!