13.09.2016 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

582 Chapter 27 Building User Authentication <strong>and</strong> Personalization<br />

As you can see, you call the register() function with the username, email address, <strong>and</strong><br />

password that were entered. If this call succeeds, you register the username as a session<br />

variable <strong>and</strong> provide the user with a link to the main members page. (If it fails, this function<br />

will throw an exception that will be caught in the catch block.) The output is<br />

shown in Figure 27.5.<br />

Figure 27.5<br />

Registration was successful; the user can now go<br />

to the members page.<br />

The register() function is in the included library called user_auth_fns.php.This<br />

function is shown in Listing 27.9.<br />

Listing 27.9 register()Function from user_auth_fns.php—This Function<br />

Attempts to Put the New User’s Information in the Database<br />

function register($username, $email, $password) {<br />

// register new person with db<br />

// return true or error message<br />

// connect to db<br />

$conn = db_connect();<br />

// check if username is unique<br />

$result = $conn->query("select * from user where username='".$username."'");<br />

if (!$result) {<br />

throw new Exception('Could not execute query');

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

Saved successfully!

Ooh no, something went wrong!