Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lecture 1: Introduction To PHP - Part I: Integrative Programming Lectures & Practice Exercises

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 19

Integrative Programming Page 1 of 19

Lectures & Practice Exercises

Lecture 1: Introduction to PHP – Part I

What is PHP?
 PHP originally meant “Personal Home Page” as it was created in 1994 by Rasmus Lerdorf to track the visitors to his
online resume.
 As its usefulness and capabilities grew (and as it started being used in more professional situations), it came to mean
“PHP: Hypertext Preprocessor.”

PHP is an HTML embedded scripting language.


 HTML embedded means that PHP can be interspersed within HTML which makes developing dynamic Web sites more
accessible.
 PHP is scripting language as opposed to a programming language. It is designed to do something only after an event
occurs—for example when a user submits a form or goes to a URL.
 PHP is a server-side, cross-platform technology. Server-side refers to the fact that everything PHP does occurs on the
server (as opposed to the client, which is the Web site viewer’s computer). Its cross-platform nature means that PHP
runs on most operating systems, including Windows, UNIX (any variants), and Macintosh.
 PHP scripts written on one server will normally work on another with little or no modifications.
Basic Syntax
 To place PHP code within a document, surround the code with PHP tags, either the formal (XML style):
<?php
?>
 or the informal:
<?
?>
 Anything placed within these tags will be treated by the Web server as PHP (meaning the PHP interpreter will process
the code rather than it being immediately sent to the Web browser).
 PHP files must use an extension that the server knows to treat as a PHP page. Standard HTML pages use .html or
.htm extension and normally, .php is preferred for PHP scripts.

Sending Data to the Web Browser


 PHP has a number of built-in functions written specifically, the most common are echo() and print().
 First Example: Open text editor and type the code below. Save it as “first.php”.
<html> <head> <title> PHP Test: First Example </title> </head>
<body>
<?php
print "Hello World!<br>";
print "I'm in <b>RTU!</b><br>";
echo 'She said, "How are you?"<br>';
print "I'm just fine.<br>";
?>
</body>
<html>
Integrative Programming Page 2 of 19
Lectures & Practice Exercises

 Using gmdate(): Open first.php and add this line after the last print:
<html> <head> <title> PHP Test: First Example </title> </head>
<body>
<?php
print "Hello World!<br>";
print "I'm in <b>RTU!</b><br>";
echo 'She said, "How are you?"<br>';
print "I'm just fine.<br>";
print "Today’s date is ";
echo gmdate("M d Y");
?>
</body>
<html>
 Output of “first.php”:

 Use the table below to modify date and time functions:


a Displays “am” or “pm”
A Displays “AM” or “PM”
d Gives the day of the month, 2 digits with leading zeros; that is, “01” to “31”
D Shows the day of the week, textual, 3 letters; for example “Fri”
F Displays month, textual, long; for example “January”
h Shows the hour, 12-hour format; that is “01” to “12”
H Shows the hour, 24-hour format; that is “00” to “23”
g Shows the hour, 12-hour format without leading zeros; that is “1” to “12”
G Shows the hour, 24-hour format without leading zeros; that is “0” to “23”
i Displays the minutes; that is “00” to “59”
j Gives the day of the month without leading zeros; that is “1” to “31”
l Gives the day of the week, textual, long; for example, “Friday”
L Boolean for whether it is a leap year; that is “0” to “1”
m Shows the month; that is “01” to “12”
n Shows the month without leading zeros; that is “1” to “12”
M Gives the month, textual, 3 letters; that is “Jan”
s Displays the seconds; that is “00” to “59”
S English ordinal suffix, textual, 2 characters; that is “th”, “nd”
t Shows the number of days in a given month; that is “28” to “31”
T Shows the Time Zone setting of the machine; for example, “MDT”
U Displays the seconds since the epoch
w Shows the day of the week, numeric; that is “0” (Sunday) to “6” (Saturday)
Y Displays the year, 4 digits; for example “2006”
y Displays the year, 2 digits; for example “06”
z Shows the day of the year; that is “0” to “365”
Z Gives the Time Zone offset in seconds; that is “-43200” to “43200”

Writing Comments
Integrative Programming Page 3 of 19
Lectures & Practice Exercises

 PHP supports three comment types. First is similar to comments in shell scripts (from Unix) and uses the pound or
number symbol(#). The second stems from the C++ programming language. The third comment style—arising from
C—allows for comments to run over multiple lines. Examples, respectively:
# This is comment.
// This is also a comment.
/* This is a larger comment
that spans two lines. */
Using Variables
 Variables are widgets used to temporarily store values. These values can be numbers, text, or much more complex
arrangements. There are eight types of variables in the PHP language. These include four-scalar (single-valued)
types—Boolean (TRUE or FALSE), integer, floating point (decimals), and strings (text): two non-scalar (multi-valued)
—arrays and objects; plus resources. All variables in PHP follow certain syntactical rules:
o A variable’s name must start with a dollar sign ($), for example, $name.
o The name can contain a combination of strings, numbers, and the underscore, example, $my_report.
o The first character after the dollar sign cannot be a number (it must be either a letter or an underscore).
o Variable names in PHP are case-sensitive. So $name and $Name are entirely different variables.
o Variables can be assigned values using the equals sign (=).
 STRINGS: A string is merely a quoted chunk of letters, numbers, spaces, punctuation, etc. Below are examples of
assigning a string value to variables and printing out their values.
 Concatenating Strings: Concatenation is addition for strings and is performed using the period (.). If assigning
another value to an existing variable, say ($book), the new value will overwrite the old one. If concatenating one
value to another, the concatenation assignment operator (.=) is used.
 STRINGS: PHP has a slew of useful string-specific functions:
o strlen() – returns a number how long a string is (characters it contain).
o strtolower() – returns a string converted entirely into lowercase characters.
o strtoupper() – returns a string converted entirely into uppercase characters.
o ucwords() – capitalizes the first character of every word.
 Second Example: Open text editor and type the code below. Save it as “variables.php”.
<html> <head> <title> PHP Test: Variables </title> </head>
<body bgcolor=black> <font color=white>
<?php
echo "<b>Using String Variables</b><br>";
print "Today’s date is ";
echo gmdate("M d Y");
echo "<br>";

$skul = "Rizal Technological University";


$kors = "BS Computer Science";
$klas = "Integrative Programming Using PHP";
echo "I go to $skul.<br>";
echo "My course is $kors.<br>";
echo "I attend the class: ITP222-$klas. <br><br>";

echo "<b>Using String Concatenation</b><br>";


$first_name = "J.K.";
$last_name = "Rowling";
$author = $first_name . " " . $last_name;
$book = "Harry Potter";
echo "The book <i> $book </i> is written by $author. <br><br>";

echo "<b>Using Concatenation Assignment Operator </b><br>";


$title = "Harry Potter:";
$subtitle = " The Goblet of Fire";
$title .= $subtitle;
Integrative Programming Page 4 of 19
Lectures & Practice Exercises

echo "$title<br> OR: <br>";


$t2 = "The Lord of The Rings:";
$s2 = "Return of the King";
$t = $t2;
$t .= " ";
$t .= $s2;
echo "$t <br><br>";
echo "<b>Using String Functions</b><br>";
$name = "LeA ANtOiNe S. vAlDeRaMa";
$n = strlen($name);
$l = strtolower($name);
$u = strtoupper($name);
$w = ucwords($name);
echo "<i>$name</i> has $n characters.<br>";
echo "<i>$name</i> in lowercase: $l.<br>";
echo "<i>$name</i> in uppercase: $u.<br>";
echo "<i>$name</i> using <i>ucwords()</i>: $w.<br><br>";
?>
</font>
</body>
</html>
 Output of “variables.php”:

 NUMBERS: PHP has both integer and floating-point (decimal) number types. Some number functions are
round()are number_format(). Example:
$n = 3.14;
$n = round($n); //3 or to a specified number of decimal places
$n = 3.142857;
$n = round ($n, 3); //3.143
$m = 23000;
$m = number_format($m); //23,000
 NUMBERS: Arithmetic Operators:
Operator Meaning
Integrative Programming Page 5 of 19
Lectures & Practice Exercises

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
 CONSTANTS: Constants are a specific data type in PHP which unlike variables, retain their initial value throughout
the course of a script. The value of the constant cannot be changed once has it been set. To create a constant, use
the define()function instead of the assignment operator for variables.
 ESCAPE CHARACTERS:
Code Meaning
\" Double quotation mark
\' Single quotation mark
\\ Backslash
\n Newline
\r Carriage return
\r Tab
\$ Dollar sign
 Single and Double Quotation Marks: In PHP, values enclosed within single quotation marks will be treated
literally, whereas those within double quotation marks will be interpolated. Placing variables and special characters
within double quotes will have their represented values printed, not their literal values.
 Third Example: Open text editor and type the code below. Save it as “numbers.php”.
<html> <head> <title> PHP Test: Using Numbers </title> </head>
<body bgcolor=black> <font color=white>
<?php
echo "<b>Using Numbers </b><br>";
print "Today’s date is ";
echo gmdate("M d Y");
echo "<br>";
$quantity = 30; // 30 pcs.
$price = 119.95; // $119.95
$taxrate = .05; // 5% tax rate
$total = $quantity * $price;
$total = $total + ($total * $taxrate); // Add tax
$total = number_format ($total, 2); // Format the results
echo "You are purchasing <b> $quantity </b> widgets at a cost of <b>\$ $price</b>
each.<br>";
echo "With tax, the total comes to <b>\$ $total </b><br><br>";
echo "<b>Using define() Function</b><br>";
define ("YEAR", "2005");
define ("INDAY", "July 4th");
echo "US Independence Day is " . INDAY . "<br>";
echo "We are in year " . YEAR . ".<br>";
echo "This server is running version " . "<b>" . PHP_VERSION . " of the PHP on the "
. PHP_OS . ".</b><br><br>";
echo "<b>Single and Double Quotation Marks</b><br>";
$var = 'test';
echo "var is equal to $var <br>";
echo 'var is equal to $var <br>';
?>
</font>
</body>
</html>
Integrative Programming Page 6 of 19
Lectures & Practice Exercises

 LABORATORY EXERCISES:
 Create a folder named after your SURNAME under the directory c:/Program Files/Apache
Group/Apache/htdocs/VALDERAMA
 Create the following Sample Exercises first:
O FIRST_INITIALSPC# (EX. FIRST_AV60.PHP)
O VARIABLES_INITIALSPC# (EX. VARIABLES_AV60.PHP)
O NUMBERS_INITIALSPC# (EX. NUMBERS_AV60.PHP)
 Then solve the exercise below. Save it in just one .PHP file using the filename: EXER01INITIALSPC# (EXAMPLE:
EXER01AV60.PHP)
 Write a PHP code that will display the following:
a. complete date and time today;
b. your complete name in all capital letters (using strtoupper() function); and do the FF.:
 Display the Area, Circumference, and Diameter of a circle if the radius is 23.
 Display the Area of a triangle if the base is 10 and the height is 12.
 Display the value in degrees Celsius if the degree in Fahrenheit is 50.
 Display the value of 1500 pesos in dollars if the conversion factor is $1 = P54.25
 Use the following:
1. Celsius = 5/9 * (Fahrenheit – 32)
2. Diameter = 2 * Radius
3. Circumference = 2 * Pi * Radius
4. Area (circle)= Pi * Radius * Radius
5. Area (triangle) = ½ * Base * Height
 Refer to the output below:
Integrative Programming Page 7 of 19
Lectures & Practice Exercises

Lecture 2: Introduction to PHP – Part II

Creating an HTML Form


 Managing HTML forms with PHP is a two-step process:
1. create the HTML form
2. create the appropriate PHP script that receives the form data
 An HTML form is created using the form tags and various input types. Example:
<form action=”script.php” method=”post”> … </form>
<form action=”script.php” method=”get”> … </form>
 The most important attribute of the form tag is the action, which dictates to which page the form data will be sent.
It tells the server which page to go once the user clicked a submit button on the form.
 The second attribute--method—dictates how the data is sent to the handling page. The two option values—get and
post—refer to HTTP (HyperText Transfer Protocol) method to be used. The get method sends the submitted data
to the receiving page as a series of name-value pairs appended to the URL. Example:
http://localhost/examples/handle_form.php?name=Arlene&gender=F
 The post method is identical to the GET method but the information in the form is sent in the body of the HTTP
request rather than as part of the URL.

INPUT Types in the form tag:


 TextFields (Text Boxes)
Enter Your Name: <input type="text" name="name">
 TextArea
Enter comments here: <textarea name="comments" cols="50" rows="5"> Hi </textarea>
 Checkbox
Have you taken the Scholastic Test? <input type="checkbox" name="choice">
 Multiple Checkboxes
Have you experienced:
<input type="checkbox" name="choice1" value="Diving in Anilao"> Diving in Anilao?
<input type="checkbox" name="choice2" value="Surfing in Siargao"> Surfing in Siargao?
<input type="checkbox" name="choice3" value="Snorkling in Cebu"> Snorkling in Cebu?
 Radio Button
Select from these:
<input type="radio" name="r1" value="Microsoft"> Microsoft
<input type="radio" name="r1" value="Open Source"> Open Source
 List Boxes
<select name="price">
<option> Under P5,000 </option>
<option> P5,000-P10,000 </option>
<option> P11,000-P25,000 </option>
<option> Over P25,000 </option>
</select>
 Example HTML Form. Type the file and save it as “input_types.html”
<html> <head> <title> Use of Input Types Form Tag in PHP </title> </head>
<body bgcolor="99ffff">
<form action="input_types.php" method="post">
<b> TextFields </b> <br>
Enter Your Name:
<input type="text" name="name"> <br>
Enter Your Age: <input type="text" name="age"> <br> <br>
<b> Checkbox </b> <br>
Have you eaten an apple? <br>
<input type="checkbox" name="choice"> Yes <br> <br>
<b> Multiple Checkboxes </b> <br>
Have you experienced: <br>
Integrative Programming Page 8 of 19
Lectures & Practice Exercises

<input type="checkbox" name="choice1" value="Diving in Anilao"> Diving in Anilao? <br>


<input type="checkbox" name="choice2" value="Surfing in Siargao"> Surfing in Siargao?
<br>
<input type="checkbox" name="choice3" value="Eating a cockroach"> Eating a cockroach?
<br> <br>
<b> Radio Buttons </b> <br>
Which do you prefer most? <br>
<input type="radio" name="q1" value="Microsoft"> Microsoft <br>
<input type="radio" name="q1" value="Open Source"> Open Source <br>
<input type="radio" name="q1" value="No comment"> No comment <br> <br>
<b> List Boxes </b> <br>
Which prices do you prefer most in shopping for clothings? <br>
<select name="price">
<option> Under P200 </option>
<option> P300-P500 </option>
<option> P500-P1000 </option>
<option> Over P1000 </option>
</select> <br> <br>
<br> <br> <br> <br>
What size are you in Pants? <br>
<select name="pantsSize[]" multiple>
<option> Small </option>
<option> Medium </option>
<option> Large </option>
<option> Extra Large </option>
</select> <br> <br>
<b> TextArea </b> <br>
Enter comments here: <br>
<textarea name="w" cols="50" rows="5"> </textarea> <br> <br>
<input type="submit" value="See Results">
<input type="reset" value="Clear">
</form>
</body>
</html>
Integrative Programming Page 9 of 19
Lectures & Practice Exercises

 Type the file and save it as “input_types.php”

<html> <head> <title> Use of HTML Form Tags in PHP </title> </head>
<body bgcolor="99ffff">
<?php
echo "OUTPUT From: <b> TextField </b> <br>";
echo "Hi {$_POST['name']}!<br>";
echo "You are {$_POST['age']} years old. <br><br>";
echo "OUTPUT From: <b> Checkbox </b> <br>";
echo "Checkbox status: <b> {$_POST['choice']} </b> <br><br>";
echo "OUTPUT From: <b> Multiple CheckBoxes </b> <br>";
echo "You have experienced: <br>";
echo "&nbsp {$_POST['choice1']} <br>";
echo "&nbsp {$_POST['choice2']} <br>";
echo "&nbsp {$_POST['choice3']} <br><br>";
echo "OUTPUT From: <b> Radio Button </b> <br>";
echo "You selected: {$_POST['q1']} <br><br>";
echo "OUTPUT From: <b> List Box </b> <br>";
echo "Price Range: {$_POST['price']} <br><br>";
echo "<br>Pants Size(s): {$_POST['pantsSize[0]']}";
echo "{$_POST['pantsSize[1]']}";
echo "{$_POST['pantsSize[2]']}";
echo "{$_POST['pantsSize[3]']} <br><br>";
echo "OUTPUT From: <b> TextArea </b> <br>";
echo "{$_POST['w']} <br>";
?>
</body>
</html>
Integrative Programming Page 10 of 19
Lectures & Practice Exercises

Lecture 3: PHP and HTML Forms and Decision Making Statements

Using the IF Statement


 Practice Exercise: (guessnum_ _ _ _.html)
<html> <head> <title> Use of Decision Statements in PHP </title> </head>
<body bgcolor=cccc99>
<h2> Guess the Number Game </h2>
<form action="guessnum.php" method="post">
Think of a number from 1-10:
<input type="text" name="guess"> <br> <br>
<input type="submit" value="See If U R Correct">
</form>
</body>
</html>
 Practice Exercise: (guessnum_ _ _ _.php)
<html> <head> <title> Use of Decision Statements in PHP </title> </head>
<body bgcolor=cccc99>
<h2> Guess the Number Result </h2>
<?
$num = rand(1,10); //or you can set the value for the number, e.g. $num=5;
if ($guess > $num) {
echo "Your guess is too high. <br> It's $num. ";
}
if ($guess < $num) {
echo "Your guess is too low. <br> It's $num. ";
}
else {
echo "You're Right! <br> It's $num. ";
}
?>
</body>
</html>

 OUTPUT:

Using Nested IF Statement


 Practice Exercise: (holiday_ _ _ _.html)
<html> <head> <title> ACV Holidays </title> </head>
<body bgcolor="cccc99">
<h2> ACV Holidays </h2>
<h3> Reservation Form </h3>
<form action="holiday.php" method="post">
Integrative Programming Page 11 of 19
Lectures & Practice Exercises

<b> DESINATION </b> <br>


Choose here: <br>
<input type="radio" name="destination" value="HongKong"> HongKong <br>
<input type="radio" name="destination" value="Singapore"> Singapore <br>
<input type="radio" name="destination" value="Malaysia"> Malaysia <br> <br>
<b> HOTEL TYPE </b> <br>
Choose here: <br>
<input type="radio" name="hotel" value="three"> Three Star <br>
<input type="radio" name="hotel" value="five"> Five Star <br>
<input type="submit" value="Reserve">
<input type="reset" value="Clear">
</form>
</body>
</html>

 Practice Exercise: (holiday_ _ _ _.php)


<html> <head> <title> ACV Holidays </title> </head>
<body bgcolor="cccc99">
<h2> ACV Holidays </h2>
<h3> Reservation Form </h3>
<?php
$price = 500;
$hotelmodifier = 1;
$placemodifier = 1;

if ($hotel=="three") {
if ($destination=="HongKong") {
$hotelmodifier = 2;
$price = $price * $placemodifier;
echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}
else if ($destination=="Singapore") {
$hotelmodifier = 3.5;
$price = $price * $placemodifier;
echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}
else if ($destination=="Malaysia") {
$price = $price * $placemodifier;
echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}
else {
echo "Sorry, you have made an invalid entry.";
}
}
else if ($hotel=="five") {
if ($destination=="HongKong") {
$hotelmodifier = 2.5;
$price = $price * $placemodifier * $hotelmodifier;
echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}

else if ($destination=="Singapore") {
$hotelmodifier = 4;
$price = $price * $placemodifier * $hotelmodifier;
Integrative Programming Page 12 of 19
Lectures & Practice Exercises

echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}

else if ($destination=="Malaysia") {
$price = $price * $placemodifier * $hotelmodifier;
echo "Your reservation has been saved. <br> Your one-week holiday at $destination
costs \$$price. <br> Thank you for choosing ACV Holidays! Enjoy!";
}
else {
echo "Sorry, you have made an invalid entry.";
}
}
else {
echo "Sorry, you have made an invalid entry.";
}
?>
</body>
</html>

 The Switch Case Statement can also be used here.


 OUTPUT:

 EXERCISE: (bankloan_ _ _ _.html & bankloan_ _ _ _.php)


 Current Salary choices: Under P10000/20000/30000/40000/Over 50000
 Use the following formula:
o Salary Allowance = Salary/5
o Age Allowance = (Age/10 – (Ag e%10)/10) – 1
o Loan Allowance = Salary Allowance * Age Allowance
o IF loan <= Loan Allowance
 Display “Yes, (first name) (last name), we are delighted to accept your application”
 Otherwise, display “Sorry (first name) (last name), we cannot accept your application at this
time.”
Integrative Programming Page 13 of 19
Lectures & Practice Exercises

 SAMPLE OUTPUT:
Integrative Programming Page 14 of 19
Lectures & Practice Exercises

Lecture 4: PHP and MySQL

PHP & MySQL


 Access the system from the command prompt interface.
 Move to the mysql/bin directory. (type cd C:\mysql\bin then press Enter)
 Type: mysqld–nt --console then press Enter
 Open another command prompt interface.
 Type: mysql –u root
 The MySQL prompt appears as the user successfully logs in. (To shutdown: mysqladmin –u root shutdown)

 Create a database following the prompt:

 Use the database; Show the current tables; and create a new table;

 Describe table to show the rows;


Integrative Programming Page 15 of 19
Lectures & Practice Exercises

 Insert values to the table rows;

 Another way of inserting values to the table rows;

 Entering data from an HTML form;


Integrative Programming Page 16 of 19
Lectures & Practice Exercises

 inputform.html
<html>
<head> <title> Sample Input Form </title></head>
<body bgcolor="cc3366" text="ffff99" vlink="ffff99">
<font face="Arial">
<center>
<form action="insertdata.php" method="post">
<table border=0 cellspacing=10>
<tr>
<td> Name: </td>
<td> <input type="text" name="name"> </td>
</tr>
<tr>
<td> Course: </td>
<td> <input type="text" name="course"> </td>
</tr>
<tr>
<td> Gender[F/M]: </td>
<td> <input type="text" name="gender"> </td>
</tr>
<tr>
<td> Email Address: </td>
<td> <input type="text" name="email"> </td>
</tr>
</table>
<input type="submit" name="submit" value="Save Entry"> &nbsp &nbsp &nbsp
<input type="reset" name="reset" value="Clear"> &nbsp &nbsp &nbsp
</form>
<a href="viewrecords.php" onMouseover="window.status='View Records'; return true" onMouseout="window.status=' ';
return true"> View Records </a> &nbsp &nbsp
</html>

 The database is thus updated;

 The database is thus updated;


Integrative Programming Page 17 of 19
Lectures & Practice Exercises

 insertdata.php
<html>
<head> <title> Insert Data </title>
<body bgcolor=cc3366 text=ffff99 topmargin=100 vlink=ffff99>
<font face="Arial">
<?php

$dbc = mysql_connect ('localhost','root','') OR die ('Could not select the database because: <b>' . mysql_error() .
'</b>');
mysql_select_db('db_students') OR die( 'Could not connect to MySQL because: <b>' . mysql_error() . '</b>');

$query = "INSERT INTO tb_students values ('{$_POST['name']}',


'{$_POST['course']}','{$_POST['gender']}','{$_POST['email']}','')";
$result = mysql_query($query);
print '<table border=0 align=center cellspacing=0 cellpadding=0>
<center><b> Data saved. </b></center>';
mysql_close();
?>
<a href="viewrecords.php" onMouseover="window.status='View Records'; return true" onMouseout="window.status=' ';
return true"> View Records </a>
</body>
</html>

 View the records from the browser:


Integrative Programming Page 18 of 19
Lectures & Practice Exercises

 viewrecords.php
<html> <head> <title> View Records </title></head>
<body bgcolor="cc3366" text="ffff99" vlink="ffff99">
<font face="Arial"> <center>
<?php
$dbc = mysql_connect ('localhost','root','') OR die ('Could not select the database because: <b>' . mysql_error() .
'</b>');
mysql_select_db('db_students') OR die( 'Could not connect to MySQL because: <b>' . mysql_error() . '</b>');

mysql_query('alter table tb_students add id int(50) primary key auto_increment');


//Make the query.
$query = "SELECT * FROM tb_students";

//Run the query.


$result = mysql_query($query);
$rows = mysql_numrows($result);

print '<table border=0 cellspacing=0 cellpadding=0><br><p><br><p>';


while ( $row = mysql_fetch_array($result)) {
print "<tr>
<td width=200> <b> ID </b> </td>
<td> {$row['id']} </td>
</tr>
<tr>
<td width=200> <b> Name </b> </td>
<td>{$row['name']}</td>
</tr>
<tr>
<td width=200> <b> Course </b> </td>
<td>{$row['course']}</td>
</tr>
<tr>
<td width=200> <b> Gender </b> </td>
<td>{$row['gender']}</td>
</tr>
<tr>
<td width=200> <b> Email </b> </td>
<td>{$row['email']}</td>
</tr>
<tr>
<td width=200> <a href='deletedata.php?id={$row['id']}'> Delete data </a> </td>
</tr>
<tr>
<td height='25'> <hr color=ffff99> </td>
<td><hr color=ffff99></td>
</tr>";
}
print '<tr>
<td width=200> <b> Total Number of Records: </b> </td>
<td>' . $rows .' </td>
</tr>
</table>';
?>
<a href="inputform.html" onMouseover="window.status='Add New Entry'; return true" onMouseout="window.status=' ';
return true"> Add New Entry </a> &nbsp &nbsp
Integrative Programming Page 19 of 19
Lectures & Practice Exercises

</font> </center> </body> </html>


 Deleting a record;

 deletedata.php
<html> <head> <title> Delete data </title>
<body bgcolor=cc3366 text=ffff99 topmargin=100 vlink=ffff99>
<font face="Arial">
<?php
$dbc = mysql_connect ('localhost','root','') OR die ('Could not select the database because: <b>' . mysql_error() .
'</b>');
mysql_select_db('db_students') OR die( 'Could not connect to MySQL because: <b>' . mysql_error() . '</b>');

if (is_numeric($_GET['id'])) {
$query = "DELETE FROM tb_students where id={$_GET['id']}";
if ($r = mysql_query($query))
{
mysql_query('ALTER TABLE tb_students drop id');
print "<center><font size=6><b> Data deleted. </b></font></center>";
}
else
{
print "cannot Delete because: <b> " . mysql_error() . "</b> . The Query was $query . ";
}
}
else {
print "Could not find the Id because: <b>" . mysql_error() . "</b> . The Query was $query . ";
}
mysql_close();
?>
<br><p><br><p><br><p><br><p><br><p><br><p><br><p><br><p><br><p>
<center>
<a href="viewrecords.php" onMouseover="window.status='View Records'; return true" onMouseout="window.status=' ';
return true"> View Records </a>
<br><p>
<a href="inputform.html" onMouseover="window.status='Add New Entry'; return true" onMouseout="window.status=' ';
return true"> Add New Entry </a> </center> </body>
</html>

You might also like