0% found this document useful (0 votes)
77 views41 pages

Building Practical PHP and Mysql Project: Course: Z1167 Advanced in Web Based Application Development Year: 2019

1. The document discusses planning and running a web application project, including defining goals, audience, components, and processes. 2. It also covers debugging programming errors like syntax errors, runtime errors, and logic errors. 3. The document outlines implementing user authentication for a web application, including registering users, validating credentials, and allowing password resets.

Uploaded by

Stella Benita
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views41 pages

Building Practical PHP and Mysql Project: Course: Z1167 Advanced in Web Based Application Development Year: 2019

1. The document discusses planning and running a web application project, including defining goals, audience, components, and processes. 2. It also covers debugging programming errors like syntax errors, runtime errors, and logic errors. 3. The document outlines implementing user authentication for a web application, including registering users, validating credentials, and allowing password resets.

Uploaded by

Stella Benita
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Course : Z1167 Advanced in Web Based

Application Development
Year : 2019

Building Practical PHP and


MySQL Project

Session 11
Building Practical PHP and MySQL Project

Using PHP and MySQL for large project


Debugging
Building User Authentication and Personalization
Building a Shopping Chart
Learning Objectives

LO 2 : Build E-commerce site

LO 3 : Design planning, creating web database using MySQL


Planning and Running a Web Application Project

11.1 Planning and Running a Web Application Project


Before you begin your web application think about :
1. what you are trying to build.
2. Think about the goal.
3. Think about who is going to use your web application
that is, your targeted audience.
4. Whether users were interested in such an application.
5. Try to break down your application into components.
6. What parts or process steps does your application
have?
7. How will each of those components work?

Bina Nusantara University 4


Planning and Running a Web Application Project

8. Make decisions about process issues. This step is


ignored too often in web projects.
9. By process issues, we mean, for example, coding
standards, directory structures,
10. Management of version control, development
environment, documentation level and standards, and
task allocations to team members.
11. Make any optimizations you think are necessary.

Bina Nusantara University 5


Planning and Running a Web Application Project

11.2 Documenting Your Projects


Documentation for your programming projects, including,
but not limited to, the following:
1. Design documentation
2. Technical documentation/developer’s guide
3. Data dictionary (including class documentation)
4. User’s guide (although most web applications have to
be self-explanatory).

Bina Nusantara University 6


Debugging

11.3 Programming Errors


Regardless of which language you are using, there are
three general types of program errors:
 Syntax errors
 Runtime errors
 Logic errors

Bina Nusantara University 7


Debugging

Syntax error
 If a statement does not follow the rules of a language.
 Syntax errors are often also called parser errors when
discussing interpreted languages, such as PHP, or
compiler errors when discussing compiled languages,
such as C or Java.
This error was produced by the following script:
<?php
$date = date(m.d.y’);
?>

Bina Nusantara University 8


Debugging

Runtime errors
• Runtime errors are not caused solely by the contents
of your script. They can rely on interactions between
your scripts and other events or conditions.
• The statement require (‘filename.php’);
is a perfectly valid PHP statement. It contains no
syntax errors.
• This statement might, however, generate a runtime
error. If you execute this statement and filename.php
does not exist or the user who the script runs as is
denied read permission, you will get an error
resembling this one:

Bina Nusantara University 9


Debugging

• Although nothing is wrong with the code here,


because it relies on a file that might or might not exist
at different times when the code is run, it can generate
a runtime error.
• The following three statements are all valid PHP.
Unfortunately, in combination, they attempt to do the
impossible—divide by zero:
$i = 10;
$j = 0;
$k = $i/$j;

Bina Nusantara University 10


Debugging

Logic errors
• Logic errors can be the hardest type of error to find
and eliminate.
• This type of error occurs when perfectly valid code
does exactly what it is instructed to do, but that was
not what the writer intended.
• Logic errors can be caused by a simple typing error,
such as
for ( $i = 0; $i < 10; $i++ );
{
echo ‘doing something<br />’;
}

Bina Nusantara University 11


Implementing User Authentication

11.4 Registering
Several alternatives can be used for user authentication
1. Users should be able to register their usernames and
passwords.
2. You need some restrictions on the length and format
of each username and password.
3. You should store passwords in an encrypted format
for security reasons.
4. Users should be able to log in with the details they
supplied in the registration process.
5. Users should be able to change their passwords as an
aid to security.

Bina Nusantara University 12


Implementing User Authentication

6. Users will occasionally forget their passwords. They


should be able to reset their passwords without
needing personal assistance from you.
7. A common way of doing this is to send a user’s
password to him in an email address he has
nominated at registration. This means you need to
store his email address at registration.
8. Because you store the passwords in an encrypted
form and cannot decrypt the user’s original
password, you actually need to generate a new
password, set it, and mail it to the user.

Bina Nusantara University 13


Implementing User Authentication

• To register a user, you need to get his details via a


form and enter him in the database.
• When a user clicks on the Not a member? link on the
login.php page, he is taken to a registration form
produced by register_form.php

Bina Nusantara University 14


//email address not valid //
if (!valid_email($email))
{
throw new Exception(‘That is not a valid email address.
.’ and try again.’);
}
Please go back ‘
// passwords not the same
if ($passwd != $passwd2)
{
throw new Exception(‘The passwords you entered do not match
.’ - please go back and try again.’);
}
// check password length is ok
if (strlen($passwd)<6)
{
throw new Exception(‘Your password must be at least 6 characters
long.’
.’Please go back and try again.’);
}
// check username length is ok
if (strlen($username)>16)
{
throw new Exception(‘Your username must be less than 17
characters long.’
.’Please go back and try again.’);
Bina Nusantara University } 15
Implementing User Authentication

Login
• If users type their details into the form at login.php and
submit it,they will be taken to the script called
member.php
Function login($username, $password)
// check username and password with db
// if yes, return true
// else throw exception
{
// connect to db
$conn = db_connect();
// check if username is unique
$result = $conn->query(“select * from user
where username=’$username’
and passwd = sha1(‘$password’)”);
if (!$result)
throw new Exception(‘Could not log you in.’);
if ($result->num_rows>0)
return true;
else
throw new Exception(‘Could not log you in.’);
Bina Nusantara University } 16
function check_valid_user()
// see if somebody is logged in and notify them if not
{
if (isset($_SESSION[‘valid_user’]))
{
echo ‘Logged in as ‘.stripslashes($_SESSION[‘valid_user’]).’.’;
echo ‘<br />’;
}
else
{
// they are not logged in
do_html_heading(‘Problem:’);
echo ‘You are not logged in.<br />’;
do_html_url(‘login.php’, ‘Login’);
do_html_footer();
exit;
}
}

Bina Nusantara University 17


Implementing User Authentication

Logging Out
<?php
// include function files for this application
require_once(‘bookmark_fns.php’);
session_start();
$old_user = $_SESSION[‘valid_user’];
// store to test if they *were* logged in
unset($_SESSION[‘valid_user’]);
$result_dest = session_destroy();

// start output html


do_html_header(‘Logging Out’);
if (!empty($old_user))
{
if ($result_dest)
{
// if they were logged in and are now logged out
echo ‘Logged out.<br />’;
do_html_url(‘login.php’, ‘Login’);
}

Bina Nusantara University 18


else
{
// they were logged in and could not be logged out
echo ‘Could not log you out.<br />’;
}
}
else
{
// if they weren’t logged in but came to this page somehow
echo ‘You were not logged in, and so have not been logged out.<br />’;
do_html_url(‘login.php’, ‘Login’);
}

Bina Nusantara University 19


Implementing User Authentication

Changing Passwords

Bina Nusantara University 20


function change_password($username, $old_password, $new_password)
// change password for username/old_password to new_password
// return true or false
{
// if the old password is right
// change their password to new_password and return true
// else throw an exception
login($username, $old_password);

$conn = db_connect();
$result = $conn->query( “update user
set passwd = sha1(‘$new_password’)
where username = ‘$username’”);
if (!$result)
throw new Exception(‘Password could not be changed.’);
else
return true; // changed successfully

Bina Nusantara University 21


Implementing User Authentication

Resetting Forgotten Passwords


• In addition to changing passwords, you need to deal
with the common situation in which a user has
forgotten their password

Bina Nusantara University 22


function reset_password($username)
// set password for username to a random value
// return the new password or false on failure
{
// get a random dictionary word b/w 6 and 13 chars in length
$new_password = get_random_word(6, 13);
if($new_password==false)
throw new Exception(‘Could not generate new password.’);
// add a number between 0 and 999 to it
// to make it a slightly better password
srand ((double) microtime() * 1000000);
$rand_number = rand(0, 999);
$new_password .= $rand_number;
// set user’s password to this in database or return false
$conn = db_connect();
$result = $conn->query( “update user
set passwd = sha1(‘$new_password’)
where username = ‘$username’”);
if (!$result)
throw new Exception(‘Could not change password.’); // not
changed
else
return $new_password; // changed successfully

Bina Nusantara University 23


Building a Shopping Chart

11.5 Implementing the Database


create table customers
(
customerid int unsigned not null auto_increment primary key,
name char(60) not null,
address char(80) not null,
city char(30) not null,
state char(20),
zip char(10),
country char(20) not null
) type=InnoDB;

create table orders


(orderid int unsigned not null auto_increment primary key,
customerid int unsigned not null references customers(customerid),
amount float(6,2),
date date not null,
order_status char(10),
ship_name char(60) not null,
ship_address char(80) not null,
ship_city char(30) not null,
ship_state char(20),
ship_zip char(10),
ship_country char(20) not null
) type=InnoDB;
Bina Nusantara University 24
Building a Shopping Chart

create table categories


(
catid int unsigned not null auto_increment primary key,
catname char(60) not null
) type=InnoDB;
create table order_items
(
orderid int unsigned not null references orders(orderid),
isbn char(13) not null references books(isbn),
item_price float(4,2) not null,
quantity tinyint unsigned not null,
primary key (orderid, isbn)
) type=InnoDB;
create table admin
(
username char(16) not null primary key,
password char(40) not null
);

Bina Nusantara University 25


Building a Shopping Chart

11.6 Implementing the Online Catalog

Bina Nusantara University 26


//get categories out of database//
$cat_array = get_categories();
// display as links to cat pages
display_categories($cat_array);
// if logged in as admin, show add, delete, edit cat links
if(isset($_SESSION[‘admin_user’]))
{
display_button(‘admin.php’, ‘admin-menu’, ‘Admin Menu’);
}
do_html_footer();
?>
function get_categories()
{// query database for a list of categories
$conn = db_connect();
• $query = ‘select catid, catname
from categories’;
$result = @$conn->query($query);
if (!$result)
return false;
$num_cats = @$result->num_rows;
if ($num_cats ==0)
return false;
$result = db_result_to_array($result);
return $result;

Bina Nusantara University 27


Building a Shopping Chart

11.7 Implementing Shopping Chart

Bina Nusantara University 28


<?php
require (‘book_sc_fns.php’);
// The shopping cart needs sessions, so start one
session_start();
@ $new = $_GET[‘new’];

if($new)
{
//new item selected
if(!isset($_SESSION[‘cart’]))
{
$_SESSION[‘cart’] = array();
$_SESSION[‘items’] = 0;
$_SESSION[‘total_price’] =’0.00’;
}

Bina Nusantara University 29


if(isset($_SESSION[‘cart’][$new]))
$_SESSION[‘cart’][$new]++;
else
$_SESSION[‘cart’][$new] = 1;
$_SESSION[‘total_price’] = calculate_price($_SESSION[‘cart’]);
$_SESSION[‘items’] = calculate_items($_SESSION[‘cart’]);
}
if(isset($_POST[‘save’]))
{
foreach ($_SESSION[‘cart’] as $isbn => $qty)
{
if($_POST[$isbn]==’0’)
unset($_SESSION[‘cart’][$isbn]);
else
$_SESSION[‘cart’][$isbn] = $_POST[$isbn];
}
$_SESSION[‘total_price’] = calculate_price($_SESSION[‘cart’]);
$_SESSION[‘items’] = calculate_items($_SESSION[‘cart’]);
}

Bina Nusantara University 30


do_html_header(‘Your shopping cart’) ;
if($_SESSION[‘cart’]&&array_count_values($_SESSION[‘cart’]))
display_cart($_SESSION[‘cart’]);
else
{
echo ‘<p>There are no items in your cart</p>’;
echo ‘<hr />’;
}
$target = ‘index.php’;
// if we have just added an item to the cart
// continue shopping in that category
if($new)
{
$details = get_book_details($new);
if($details[‘catid’])
$target = ‘show_cat.php?catid=’.$details[‘catid’];
}

Bina Nusantara University 31


Building a Shopping Chart

11.8 Viewing The Cart


No matter which page you come from, you display the
contents of the cart. In the base case, when a user has
just clicked View Cart, the only part of the code that
will be executed follows:
if($_SESSION[‘cart’]&&array_count_values($_SESSION[‘cart’]))
display_cart($_SESSION[‘cart’]);
else
{
echo ‘<p>There are no items in your cart</p>’;
echo ‘<hr />’;
}
As you can see from this code, if you have a cart with
some contents, you will call the display_cart() function.
If the cart is empty, you’ll give the user a message to
that effect.
Bina Nusantara University 32
Building a Shopping Chart

11.9 Adding Items to the Chart


If a user has come to the show_cart.php page by clicking
an Add to Cart button, you have to do some work before
you can show her the contents of her cart. Specifically,
you need to add the appropriate item to the cart, as
follows. First, if the user has not put any items in her cart
before, she will not have a cart, so you need to create
one:
if(!isset($_SESSION[‘cart’]))
{
$_SESSION[‘cart’] = array();
$_SESSION[‘items’] = 0;
$_SESSION[‘total_price’] =’0.00’;
}
if(isset($_SESSION[‘cart’][$new]))
$_SESSION[‘cart’][$new]++;
else
$_SESSION[‘cart’][$new] = 1;
Bina Nusantara University 33
Building a Shopping Chart

11.20 Saving the Update Cart


• If the user comes to the show_cart.php script by
clicking the Save Changes button, the process is a little
different. In this case, the user has arrived via a form
submission. If you look closely at the code, you will see
that the Save Changes button is the submit button for
a form.
• This means that the user has presumably edited the
quantity values in the cart, and you need to update
them.
• If you look back at the text boxes in the Save Changes
form part of the script.

Bina Nusantara University 34


if(isset($_POST[‘save’]))
{
foreach ($_SESSION[‘cart’] as $isbn => $qty)
{
if($_POST[$isbn]==’0’)
unset($_SESSION[‘cart’][$isbn]);
else
$_SESSION[‘cart’][$isbn] = $_POST[$isbn];
}
$_SESSION[‘total_price’] = calculate_price($_SESSION[‘cart’]);
$_SESSION[‘items’] = calculate_items($_SESSION[‘cart’]);
}

Bina Nusantara University 35


Building a Shopping Chart

1.21 Checking Out


• When the user clicks the Go to Checkout button from
the shopping cart, this action activates the
checkout.php

Bina Nusantara University 36


<?php
//include our function set
require (‘book_sc_fns.php’);
// The shopping cart needs sessions, so start one
session_start();
do_html_header(‘Checkout’);
if($_SESSION[‘cart’]&&count($_SESSION[‘cart’]))
{
display_cart($_SESSION[‘cart’], false, 0);
display_checkout_form();
}
else
echo ‘<p>There are no items in your cart</p>’;
display_button(‘show_cart.php’, ‘continue-shopping’, ‘Continue Shopping’);
do_html_footer();
?>

Bina Nusantara University 37


include (‘book_sc_fns.php’);
// The shopping cart needs sessions, so start one
session_start();
do_html_header(“Checkout”);
// create short variable names
$name = $_POST[‘name’];
$address = $_POST[‘address’];
$city = $_POST[‘city’];
$zip = $_POST[‘zip’];
$country = $_POST[‘country’];
// if filled out
if($_SESSION[‘cart’]&&$name&&$address&&$city&&$zip&&$country)
{
// able to insert into database
if( insert_order($_POST)!=false )
{
//display cart, not allowing changes and without pictures
display_cart($_SESSION[‘cart’], false, 0);
display_shipping(calculate_shipping_cost());
Bina Nusantara University 38
Summary

Using PHP and MySQL for large project: Planning and Running
a Web Application Project

Debugging: Programming Errors :syntax , runtime, logic errors

Building User Authentication and Personalization: Registering,


Logging In, Logging Out, Changing Passwords, Resetting
Forgotten Passwords

Building a Shopping Chart: Implementing the Database,


Implementing the online catalog, Implementing the Shopping
Cart: viewing the cart, adding items to the cart, saving the
updated cart, checking out
References

• Robin Nixon. (2014). Learning PHP, MySQL &


JavaScript: With jQuery, CSS & HTML5 (Learning
Php, Mysql, Javascript, Css & Html5). O'Reilly Media.
ISBN:1491918667.
• Luke Welling; Laura Thomson;. 2009. PHP and MySQL
web development. Addison Wesley Longman.
ISBN:9780672329166
• http://
my.safaribooksonline.com/book/databases/mysql/97
8
0672329166/using-php-and-mysql-for-large-projects/c
h25lev1sec2
• https://codeshack.io/shopping-cart-system-php-mysql
/
Thank You

You might also like