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.

668 Chapter 29 Building a <strong>Web</strong>-Based Email Service<br />

The function that retrieves any existing accounts is get_accounts(), from the<br />

mail_fns.php library.This function is shown in Listing 29.4.<br />

Listing 29.4 get_accounts() Function from mail_fns.php—Function to Retrieve<br />

All the Account Details for a Particular User<br />

function get_accounts($auth_user) {<br />

$list = array();<br />

if($conn=db_connect()) {<br />

$query = "select * from accounts where username = '".$auth_user."'";<br />

$result = $conn->query($query);<br />

if($result) {<br />

while($settings = $result->fetch_assoc()) {<br />

array_push($list, $settings);<br />

}<br />

} else {<br />

return false;<br />

}<br />

}<br />

return $list;<br />

}<br />

As you can see, the get_accounts() function connects to the database, retrieves all the<br />

accounts for a particular user, <strong>and</strong> returns them as an array.<br />

Creating a New Account<br />

If a user fills out the account form <strong>and</strong> clicks the Save Changes button, the storesettings<br />

action will be activated. Let’s look at the event h<strong>and</strong>ling code for this from<br />

index.php. In the preprocessing stage, you execute the following code:<br />

case 'store-settings':<br />

store_account_settings($_SESSION['auth_user'], $_POST);<br />

break;<br />

The store_account_settings() function writes the new account details into the database.The<br />

code for this function is shown in Listing 29.5.<br />

Listing 29.5 store_account_settings() Function from mail_fns.php—<br />

Function to Save New Account Details for a User<br />

function store_account_settings($auth_user, $settings) {<br />

if(!filled_out($settings)) {<br />

echo "All fields must be filled in. Try again.";<br />

return false;<br />

} else {<br />

if($settings['account']>0) {

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

Saved successfully!

Ooh no, something went wrong!