You are on page 1of 110

Building an online bidding application using PHP/MySQL

Introduction
Purpose of this lecture is to show how to build an online application using PHP/ MySQL platform This lecture is intended for developers who wish to develop web-based application but not familiar with PHP syntaxes

Online bidding application


Application is an online auction system where items for bid are displayed to browsers Interested browsers create/ log-in to their account Once logged-in, bidders can submit bids for items that are auctioned

Outline
PHP basics MySQL connection Creation of accounts Managing logins Adding bid items Deleting bid items Logging out Viewing bid items Accepting bids Listing bids for each bid item

Outline Topic #1 PHP Basics

PHP basics
Background Web application architecture Basic syntax
<?php ?> tags Variables Operators

Flow Control and Looping

PHP basics-background
Server-side scripting language for the web PHP codes are embedded in HTML to dynamically generate web pages Originally stood for Personal Home Page
Changed to PHP Hypertext Processor

Database integration
MySQL, PostgreSQL, etc

Portability
Run on Linux, UNIX, Windows, MacOS platforms

PHP basics-web application architecture

To open a web page in browser:


Type in a Universal Resource Locator (URL) Click an existing link

A request is sent to the web server Web server locates the page and sends it back to the browser Browser displays the page

PHP basics-web application architecture model


Three Tiered Model
Presentation Layer
Web browser- displays and submits the data

Application Layer
Some programs or scripts which processes the data PHP, JSP, Servlets, ASP,CGI, etc.

Database Layer
Provides the data that the application layer needs May be an RDBMS, a flat file, XML documents, etc.

PHP basics- tags


<?php
Tells web server where PHP code begins

?>
Tells web server where PHP code ends

Code in between are processed Ex:


<?php echo Hello World; ?>

PHP basics- tags, an example


The code below outputs 10 + 15 = 25

PHP basics- variables


No need to declare variables Must start with dollar sign ($) Values are assigned to variables by the assignment operator =
$name=Jun Dolor; $qty=100;

PHP basics- operators


String Arithmetic Assignment Comparison Logical

PHP basics- operators, string


Concatenation
. appends strings

PHP basics- operators, arithmetic


+ addition - subtraction * multiplication / division % modulus

PHP basics- operators, arithmetic


Operator += -= *= /= %= .= Use $a += $b; $a -= $b; $a *= $b; $a /= $b; $a %= $b; $a .= $b; Equivalent to $a= $a + $b; $a = $a - $b; $a = $a * $b; $a = $a / $b; $a = $a % $b; $a = $a . $b;

PHP basics- operators, comparison


Operator == === != <> < > <= >= Name Equals Identical Not equal Not equal Less than Greater than Less than or equal to Greater than or equal to Example $a == $b $a === $b $a != $b $a <> $b $a < $b $a > $b $a <= $b $a >= $b

PHP basics- operators, logical


Operator Name Use
! && || and or NOT AND OR AND OR !$b $a && $b $a || $b $a and $b $a or $b

Result
Returns true if $b is false and vice-versa Returns true if both $a and $b are true, otherwise false Returns true if either $a or $b is true, otherwise false Same as &&, but with lower precedence Same as ||, but with lower precedence

PHP basics-arrays
Arrays are special type of variables for storing a list of data and manipulating them efficiently An array stores multiple data items, divided into a number of slots

PHP basics-initializing numerically indexed arrays


Initialization by direct assignment

Initialization by array construct Array elements can be of different types

PHP basics-initializing numerically indexed arrays 2


Arrays are usually assigned sequentially

In PHP, arrays can be assigned nonsequentially

PHP basics-using numerically indexed arrays


To access an array element, or part of an array, use a number called index or subscript Index number or subscript
Assigned to each member of the array to allow the program to access an individual member of the array Usually begins with zero and progress sequentially by whole numbers to the end of the array NOTE: Elements inside arrays are from 0 tp (sizeOfArray 1)

PHP basics-using numerically indexed arrays 2


Accessing a single element Accessing elements of an array using a for loop Accessing elements of an array using foreach loop

PHP basics-initializing stringindexed arrays


Initialization by direct assignment Initialization by array construct Accessing a single element

PHP basics-initializing stringindexed arrays 2


Accessing elements of a string-indexed array using list()/ each()

PHP basics-each()
Receives an array as a parameter Returns the current key and value pair as an array with four elements If the internal pointer for the array past the end of the array contents, each() returns FALSE Moves the array pointer to the next element Use reset() to move the array back at the first element

PHP basics-each() 2

PHP basics-list()
Used to assign multiple variables in one operation Usually used to capture values returned by each()

PHP basics-foreach()
Gives an easy way to iterate over arrays On sample code below:
For each loop, the value of the current element is assigned to $value Internal array pointer is advanced by one On the next loop, the next element is referenced

PHP basics-foreach() 2
On the sample code below:
The current elements key will be assigned to the variable $k on each loop

PHP basics- multi-dimensional arrays


PHP supports multi-dimensional arrays through array of arrays

PHP basics- flow control and looping


if if-else switch for while do-while break exit or die

PHP basics- if/ if-else statement


Statement- if:
A statement (or block of code) will execute only if a certain boolean is true

Statement if-else A statement (or block of code) will execute if a condition is true and a different statement if the condition is false

PHP basics- switch statement


Allows branching on multiple outcomes When a switch is encountered:
PHP evaluates expression and jumps to case whose selector matches the value of the expression Program executes the statements in order from that point on until a break statement is reached This skips to the statement after the first statement at the end of the switch Should none of the case is satisfied, the default block is executed
Default blocks are optional

PHP basics- for loop


Executes the same code a number of times
Syntax: for
(expression1;condition;expression2){statement/s}

Where:
Expression1 is executed at the start; the counter is initialized here Condition is the test before each iteration Expression2 is evaluated at the end of each iteration Statement/s are executed once for each iteration

PHP basics- while loop


Contains statements or block of statements to be repeated as long as the condition is true
Syntax: while(condition){statement/s}

Statements inside the loop are executed for as long as the condition take the true value

PHP basics- do while loop


Contains statement or block of statements that repeats as long as the condition is true Main difference between while and dowhile loop:
Statements within a do-while loops executes at least once

Syntax: do{statement/s}while(condition)

PHP basics- break


Terminates the enclosed switch statement and flow of control transfers to the next statement after switch This is also used to terminate for, while and do-while loops

PHP basics- exit or die


Stops the execution of the script with an optional error message

Outline Topic #2 MySQL Connection

MySQL Database Connection


Overview of database structure Connecting to MySQL database Selecting the database to use Using the require_once statement

Overview of Database connection


Database: auction Tables
tblaccount tblbiditems tblbidhistory

Table tblaccount
This will hold the account info of bidders/ auctioneers Table structure
Column accountid: integer, primary key, autoincrement Column username: string 50 chars Column password: string 50 chars

Table tblbiditems
This will hold the items auctioned for bidding Table structure
Column biditemid: integer , primary key, autoincrement Column accountid: string 50 chars
This identifies the auctioneer

Column biditem: string 50 chars Column biddesc: tiny text

Table tblbidhistory
This will hold the bid info for each item being auctioned Table structure
Column bidhistoryid: integer , primary key, auto-increment Column accountid: integer Column biditemid: integer Column bidprice: double Column dtesubmitted: datetime

Connecting to databases:
Function mysql_connect:
Creates a connection to MySQL Syntax: mysql_connect($hostname, $username,$password) Ex: $conn=mysql_connect(localhost, root,password)

Function mysql_select_db
Specifies the database in MySQL for use Syntax: mysql_select_db($database, $connection) Ex: mysql_select_db(auction, $conn)

Function die
Terminates execution of PHP script

Connecting to MySQL and selecting auction database


Create file dbconnect.inc
For code reuse, a separate file can be created to connect to the database PHP pages can call dbconnect.inc to connect yo the auction database

Reusing the database connection


Function require_once()
Loads a file into a PHP script

Outline Topic #3 Creation of Accounts

Creation of accounts
HTML form handling MySQL commands
Function mysql_query() Function mysql_error()

Adding records
SQL insert statement

HTML form handling


Create:
File index.html File addaccount.html File addaccountprocess.php
$_POST array

File index.html
First page that displays Provide the user with the option to create accounts

File addaccount.html
Displays a form for accepting new account info

File addaccountprocess.php
$_POST array
Special arrays that hold all form variables

Function mysql_query()
Executes an SQL statement on the database

Function mysql_error()
Displays error encountered when executing an SQL statement

SQL Insert
Adds a record on a database table

File addaccountprocess.php script

Create accounts:
Username: auctioneer1
This account will place items for bidding

Usernames: bidder1, bidder2


These account will bid for item auctioned off

Outline Topic #4 Managing Logins

Managing logins
SQL select statement Function mysql_num_rows Function isset() Session URL rewriting
Querystring $_GET array

Create:
File login.php File loginverify.php File checkstatus.inc File menu.php

SQL select statement


Example 1: select * from tblaccount
Selects all columns/ rows from table tblaccount

Example 2: select username, password from tblaccount


Selects columns username and password for all rows in table tblaccount

Example 3: select * from tblaccount where username=jundolor


Selects all columns from table tblaccount for all rows whose column username contains jundolor

Example 4: select accountid from tblaccount where username=media


Selects column accountid from tblaccount for all rows whose column username contains media

Function mysql_num_rows
Retrieves the number of rows from a result set Can only be used for SQL select statements

Function isset()
Checks if a variable exist Example: isset($name)
This check if the variable $name exist

Sessions
Special variables stored in web servers Allows passing of information between web pages Call the function session_start() at the start of scripts that will use sessions

URL Rewriting
Querystring
Information can be passed on by appending variable/value to the URL

$_GET array
Special array that holds all querystring values

File login.php code

File login.php browser shot

File loginverify.php code

File checkstatus.inc code

File menu.php

Outline Topic #5 Adding Items to Auction

Adding items to auction


File menu.php Create:
File addauctionitem.php File addauctionitemprocess.php

File menu.php

File addauctionitem.php code

File addauctionitem.php screen shot

File addauctionprocess.php

Outline Topic #6 Deleting Bid Items

Deleting Bid Items


Function mysql_fetch_array() Writing querystring URL to identify records to delete SQL delete statement Create:
File listauctionitems.php File: deletebiditem.php

Function mysql_fetch_array()
Fetches a row as an associative from a select query result set

Sample mysql_fetch_array() code

Writing querystring URLto identify records to delete


Auction items belonging to current account will be selected A loop will be created to go through each row Each row will hyperlink to a PHP based page for deletion To identify the row, a querystring variable will be appended to the URL

Writing querystring URLto identify records to delete- code

SQL delete statement


Example 1: delete from tblaccount
Deletes all rows on table tblaccount

Example 2: delete from tblaccount where accountid=1


Deletes only rows matching the condition

File menu.php

File listauctionitems.php

File deletebiditem.php

Outline Topic #7 Logging Out

Loggin out
Function session_destroy() Create:
File logout.php

Function session_destroy()
Terminates all session variables stored in server memory

File menu.php

File logout.php
Once logout.php is called, all session variable will be dropped from server memory Browser will not be able to access any page calling checkverify.php (ex: menu.php)

Outline Topic #8 Viewing Bid Items

Viewing bid items


Establishing relations between tables SQL natural join clause Create:
File listbiditems.php

Establishing relations
Table tblbiditem
Holds the items being auctioned off Column accountid identifies the owner if the auctioned item

Table tblaccount
Holds account information of the owner of the item being auctioned

Column accountid
Links the owner of the account to the auction item

SQL natural join clause


Used with SQL select statement Connects rows between different tables via their common column

File menu.php

File listbiditems.php
All items with their respective owners being auction are listed Each item will hyperlink to a PHP page for accepting bids
Accepting bids will be covered in the next topic section

Each hyperlink will append a querystring variable to identify it in the PHP page for accepting bids

File listbiditems.php code

File listbiditems.php screen shot

Outline Topic #9 Accepting Bids

Accepting bids
Using hidden fields to store ID numbers MySQL now() function Create:
File acceptbid.php File acceptbidprocess.php

Hidden fields
Not displayed to the browser Used to pass constant values

File acceptbid.php
Place the id of the auction item in a hidden field

File acceptbid.php screen shot

File acceptbid.php HTML generated code

MySQL now() function


Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format
depending on whether the function is used in a string or numeric context

The value is expressed in the current time zone.

File acceptbidprocess.php

Resulting records

Outline Topic #10 Listing Bids For Each Bid Item

Listing bids for each bid item


MySQL date_format() function Relating information from two or more tables SQL order by clause

MySQL date_format() function


Formats a string based on a specified format The following are some of the specifies of the format string:
%D: Day of month with English suffix %d: Numeric day of month (0131) %M: Month name (JanuaryDecember) %m: Month numeric (0112) %Y: Year (4 digits) %y: Year (2 digits)

MySQL date_format() sample

You might also like