Lecture 10 PHP (Detailed)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 119

PHP

Introduction
• PHP gives you the freedom to add advanced
features to your website.
• PHP can be used in many contexts - discussion
forums, polls, shops, SMS gateways, mailing
lists, etc. The only limitation with what you
choose to do with PHP is your imagination.
• PHP is not hard to learn, but be aware that
PHP is more sophisticated and demanding to
learn than HTML.
What is needed?
• It is assumed that you already have a text
editor and know how it is used.
• Next, you need access to a computer or a
server that can run PHP. In contrast to HTML
and CSS, PHP is not affected by which browser
your visitors use, but by the type of server
that's hosting your pages. This is because PHP
is a server-side technology.
What is PHP?
• PHP was originally an acronym for Personal
Home Pages, but is now a recursive acronym for
PHP: Hypertext Preprocessor.
• PHP was originally developed by the Danish
Greenlander Rasmus Lerdorf, and was
subsequently developed as open source. PHP is
not a proper web standard - but an open-source
technology. PHP is neither a real programming
language - but PHP lets you use so-called
scripting in your documents.
• To describe what a PHP page is, you could say
that it is a file with the extension .php that
contains a combination of HTML tags and scripts
that run on a web server.
How does PHP work?
• The best way to explain how PHP works is by
comparing it with standard HTML.
• Imagine you type the address of an HTML
document (e.g.
http://www.cuz.ac.zw/page.htm) in the
address line of the browser.
• This way you request an HTML page. It could
be illustrated like this:
• The server first reads the PHP file carefully to see
if there are any tasks that need to be executed.
• Only when the server has done what it is
supposed to do, the result is then sent to the
client.
• It is important to understand that the client only
sees the result of the server's work, not the
actual instructions.
• This means that if you click "view source" on a
PHP page, you do not see the PHP codes - only
basic HTML tags.
• Therefore, you cannot see how a PHP page is
made by using "view source".
Servers
• PHP is a server-side technology. Therefore,
you need to have a server to run PHP.
• But it doesn't need to cost you anything to
make this upgrade and there are several
options for doing so.
XAMPP
• XAMPP is a program that makes it easy and
possible to run PHP directly on your computer
without having to install PHP.
Installing XAMPP
• Run the installer file
• You don’t need to choose any "Service
Sections“
• Click "Finish" when the installation process is
complete
• When you have installed XAMPP, you can start
the server and save your future PHP
documents in the folder c:\xampp\htdocs on
your computer and access them in the
browser with the address http://localhost.
Testing PHP installation
• You can test whether XAMPP runs properly by
following the steps below:
1. Open the program XAMPP Control Panel
2. Start the Apache server and the MySQL server
3. Create a file in Notepad (or similar text editor) named
test.php (note that the file extension must be ".php" instead
of ".htm").

4. Insert the following code in the file:

<?php echo "Hello World!"; ?>

5. Save the file in the folder "c:\xampp\htdocs".

6. Open the file in your browser with the address


http://localhost/test.php.

•If the browser writes "Hello World!" the installation is


successful, and you're ready to run PHP on your computer.
Otherwise, see below for how to fix common problems
Saving PHP files
• You should always save your files in the
"htdocs"-folder.
• If you have made a standard installation in
Windows the path is "c:\xampp\htdocs\":
• In Notepad choose "Save as..." under "File" in
the top menu.
• Find the "\htdocs\" folder (click on the
folder-icon next to the path (see image
above), and type: "C:\xampp\htdocs")
• Choose "All Files" in the "Save as type" box.
This is very important - otherwise, you save it
as a text document and not as an PHP file.
• Now save your document as i.e. "page.php"
(the ending ".php" indicates that it is an PHP
file).
Your first PHP page
• Basically, a PHP file is a text file with the
extension .php which consists of:
– Text
– HTML tags
– PHP Scripts
Example: Hello World!
• Start by making an ordinary HTML document,
but name the file page.php and save it in the
root of the site:
• If you use XAMPP the path for the root is
"c:\xampp\htdocs\page.php" on your
computer (which is now a server).
<html>
<head>
<title>My first PHP page</title>
</head>
<body>

</body>
</html>
• PHP is all about writing commands to a
server.
• To write a command to a server, we need to
tell the server when the PHP will start and
end.
• In PHP you use the tags <?php and ?> to mark
the start and end of the PHP codes that the
server must execute (on most servers it will be
suficient to use just <? as start tag, but <?php
is the most correct to use the first time PHP is
used.)
• Now try to add the following simple code snippet to your
HTML code:
<html>
<head>
<title>My first PHP page</title>
</head>
<body>

<?php

echo "<h1>Hello World!</h1>";

?>

</body>
</html>
• When we look at the PHP document in a
browser, it should look like this:
• But it gets interesting when you look at the
HTML code in the browser (by selecting "view
source"):
Let's look at what happened
• We asked the server to write <h1> Hello
World!</h1>.
• In a more technical language, one would say
that we used the string function echo to write
a specified string to the client where the
semicolon ends the command.
Example: Now!
• Let's make the server write something else.
We could, for example, ask it to write the
current date and time:
<html>
<head>
<title>My first PHP page</title>

</head>
<body>

<?php

echo date("r");

?>

</body>
</html>
r is formatting: » RFC 2822 formatted date Example: Thu, 21
Dec 2000 16:01:07 +0200
• We make the server write the date and time
when the PHP page is displayed.
– Note that if you refresh the page in the browser, a
new time is written. The server writes the current date
and time each time the page is sent to a client.
• It is also important to note that the HTML code
contains only the date - not the PHP codes
– Therefore, the example is not affected by which
browser is used. Actually, all functionalities that are
made with server-side technologies always work in all
browsers!
• And again, notice the semicolon after the code
line. It is a separator and very important to
include - otherwise the script won't work.
Extending the example
• Let's try to extend the example by writing
both a string and a function - separated by "."
(a period) - it's done like this:
<html>
<head>
<title>My first PHP document</title>
</head>
<body>

<?php

echo "<p>Current date and time: " . date("r") . "</p>";

?>

</body>
</html>
Working with time and dates
• There are many different options for working
with date and time.
• PHP provides a wide range of functions in
relation to time and date.
• With different parameters, the date function
can return the current date / time in many
different formats.
Time and date functions
• date("y") - Returns the current year from a
date - with today's date, it returns: 17
• date("m") - Returns the current month from a
date - with today's date, it returns: 05
• date("n") - Returns the current month from a
date without leading zeroes ( eg. "1" instead
of "01") - with today's date, it returns: 5
• date("F")- Returns the current month name
from a date - with today's date, it returns:
May
• date("d") - Returns the current day of the
month from a date - with today's date, it
returns: 16
• date("l") - Returns the name of the current
weekday from a date - with today's date, it
returns: Tuesday
• date("w") - Returns the current day of the
week from a date - with today's date, it
returns:
• date("H")- Returns the current hour from a
time - with the current time, it returns: 09
• date("i") - Returns the current minute from a
time - with the current time, it returns: 42
• date("s") - Returns the current second from a
time - with the current time, it returns: 30
Loops
• In PHP, it is possible to manage the execution
of scripts with different control structures.
• Loops can be used to repeat parts of a script a
specified number of times or until a certain
condition is met.
"while" loops
• Syntax: while (condition) {
Statement
}
<html>
<head>
<title>Loops</title>
</head>

<body>
<?php
$x = 1;
while ($x <= 5) {
echo "<p>This text is repeated 5 times</p>";
$x = $x + 1;
}
?>
</body>

</html>
"for" loops
for (Initialization; Condition; Step) {
Statement
}
<html>
<head>
<title>Loops</title>
</head>

<body>
<?php
for ($x=0; $x<=5; $x=$x++) {
echo '<p>variable $x is now = ' . $x . '</p>';
}
?>
</body>
</html>
What is the output?
<html>
<head>
<title>Loops</title>
</head>

<body>
<?php
for ($x=1; $x<=6; $x=$x+1) {
echo "<h" . $x . ">Heading level " . $x . "</h" . $x . ">";
}
?>
</body>
</html>
Conditions
• Conditions are used to execute part of a script
only if some predefined requirements
(conditions) are fulfilled.
• For example, a condition could be that a date
must be after January 1, 2012 or that a
variable is greater than 7.
If…
if (condition) {
statement
}
<html>
<head>
<title>Loops </title>
</head>

<body>
<?php
$x = 2;
if ($x > 1) {
echo "<p>variable $x is greater than 1 </p>";
}
?>
</body>
</html>
If… else…
if (condition) {
statement
}
else {
statement
}
<html>
<head>
<title>Conditions</title>
</head>

<body>
<?php
if (date ("m") == 3) {
echo "<p>Now it's spring!</p> ";
}
else {
echo "<p>I do not know what season it is!</p> "; }
?>
</body>

</html>
Comparison operators
== Equals
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
Logical operators
• && And
|| Or
! Not
<html>
<head>
<title>Conditions</title>
</head>

<body>
<?php
if (date("m") >= 3 && date("m") <= 5) {
echo "<p> Now it's spring!</p> ";
}
else {
echo "<p> Now it's either winter, summer or autumn!</p> ";
}
?>

</body>

</html>
if ... elseif ... else...
<?php

if (date("m") >= 3 && date("m") <= 5) {


echo "<p>Now it's spring!</p>";
}

elseif (date("m") >= 6 && date("m") <= 8) {


echo "<p>Now it's summer!</p>";
}

elseif (date("m") >= 9 && date("m") <= 11) {


echo "<p>Now it's autumn!</p>";
}

else {
echo "<p>Now is winter!</p>";
}

?>
switch ... case
switch (expression) {

case 1:
statement
break;
case 2:
statement
break;
default:
statement
break;
}
In-class Assignment
Write a running php script using a case
statement to output:
1. days of the week using date(“w”) function as
the case
2.Months of the year using date(“m”) function as
the case
Commenting scripts
Why is it important
• When you are coding, you are writing commands to a
server/computer and need to use a highly formal
language that may not clearly reflect your thoughts
when making the script.
• Therefore, it can be difficult for others (or yourself) to
understand how the script is structured, and thus hard
to identify and correct errors in the script.
• Comments can be used to write short explanatory text
in the script. The server completely ignores the
comments, and the comments do not affect the actual
functionality of the script.
• In the business world, it is often a requirement that
scripts and programming are commented, otherwise it
would be too risky for a company to take over a system
in which it would be too difficult to find and correct
errors.
How to do it
• It is quite easy to insert a comment.
• You simply start the comment with a double
slash: "//".
<?php
// Here we write color codes using three loops
// Red can be between 0 and 255
for ($intRed=0; $intRed<=255; $intRed=$intRed+30) {
// Green can be between 0 and 255
for ($intGreen=0; $ intGreen<=255; $intGreen=$intGreen+30) {
// Blue can be between 0 and 255
for ($ intBlue=0; $intBlue<=255; $intBlue=$intBlue+30) {
// The color code is made on the form rgb(red,green,blue)
$strColor = "rgb(" . $intRed . "," . $intGreen . "," . $intBlue . ")"
// Now we write the color code to the client
echo "<span style='color:" . $strColor . "'> " . $strColor . " </span>";
// Closes the loops
}
}
}
?>
Functions
What is a function?
• A function process inputs and returns an output.
• It can be useful if, for example, you have a wide
range of data you have processed or if you have
calculations or routines that must be performed
many times.
• A function has the following syntax:
Function Name(list of parameters) {
Statement
}
Example: simple function to add the
value 1 to a number
function AddOne($x) {
$x = $x + 1;
echo $x;
}
•Our function is named AddOne and must be
called with a number - e.g. 34....
echo AddOne(34);
Example : Function with more
parameters
<?php

function AddAll($number1,$number2,$number3) {
$plus = $number1 + $number2 + $number3;
return $plus;
}

echo "123 + 654 + 9 equals " . AddAll(123,654,9);

?>
Passing variables in a URL
• When you work with PHP, you often need to
pass variables from one page to another.
How does it work?
• Maybe you have wondered why some URLs look
something like this:
http://html.net/page.php?id=1254
• Why is there a question mark after the page
name?
• The answer is that the characters after the
question mark are an HTTP query string.
• An HTTP query string can contain both variables
and their values.
• In the example above, the HTTP query string
contains a variable named "id", with the value
"1254".
http://html.net/page.php?name=Joe
How to get the variable with PHP?
• Let's say you have a PHP page named
people.php.
• Now you can call this page using the following
URL:
people.php?name=Joe
• With PHP, you will be able to get the value of
the variable 'name' like this:
$_GET["name"]
<?php

// The value of the variable name is found


echo "<h1>Hello " . $_GET["name"] . "</h1>";

?>
Several variables in the same URL
• You are not limited to pass only one variable
in a URL. By separating the variables with &,
multiple variables can be passed:
people.php?name=Joe&age=24
• How can you get the variables?
• $_GET["name"]
• $_GET["age"]
<html>
<head>
<title>Query string </title>
</head>
<body>

<?php

// The value of the variable name is found


echo "<h1>Hello " . $_GET["name"] . "</h1>";

// The value of the variable age is found


echo "<h1>You are " . $_GET["age"] . " years old </h1>";

?>

</body>
</html>
Passing variables with forms
• Interactive websites require input from users.
• One of the most common ways to get input is
with forms.
• When you code a form, there are two
particular important attributes: action and
method.
• action: Is used to enter the URL where the
form is submitted. It would be the PHP file
that you want to handle the input.
• method: Can either have the value "post" or
"get", which are two different methods to
pass data.
– At this point, you don't need to know much about
the difference, but with "get", the data is sent
through the URL, and with "post", the data is sent
as a block of data through standard input service
(STDIN).
– In the last lesson, we looked at how data is
retrieved through the URL using $_GET.
– In this lesson, we look at how data submitted
through a form using the method "post" is
retrieved.
An HTML page with a form
• The page that contains the form doesn't need
to be a PHP file (but it can be … and its
recommended that it be). It need not even be
on the same site as the file that will receive
the data.
• In our first example, we will look at a very
simple form with one text field:
<html>
<head>
<title>Form</title>
</head>
<body>

<h1>Enter your name</h1>

<form method="post" action="handler.php">


<input type="text" name="username">
<input type="submit">
</form>

</body>
</html>
Result
Requesting form data with PHP
• When you need to request data submitted
through a form (post method), you use
$_POST:
$_POST["fieldname"];
• Which returns the value of a field in the form
Example
• First create a page with a form as above.
• Then make a PHP page named "handler.php"
(notice that this is the name of the page we
wrote in the action attribute in our <form>).
• The file "handler.php" shall have the following
content:
handler.php
<html>
<head>
<title>Form</title>
</head>

<body>

<?php

echo "<h1>Hello " . $_POST["username"] . "</h1>";

?>

</body>
</html>
User input and conditions
• In the next example, we will try to use user
input to create conditions.
• First, we need a form:
<html>
<head>
<title>Form</title>
</head>
<body>

<form method="post" action="handlers.php">

<p>What is your name:</p>


<input type="text" name="username"></p>

<p>What is your favorite color:


<input type="radio" name="favoritecolor" value="r" /> Red
<input type="radio" name="favoritecolor" value="g" /> Green
<input type="radio" name="favoritecolor" value="b" /> Blue </p>

<input type="submit" value="Submit" />

</form>

</body>
</html>
• Now we will use these inputs to create a page
that automatically changes background color
according to what the user's favorite color is.
• We can do this by creating a condition that
uses the data the user has filled out in the
form.
<?php

$strHeading = "<h1>Hello " . $_POST["username"] . "</h1>";

switch ($_POST["favoritecolor"]) {
case "r":
$strBackgroundColor = "rgb(255,0,0)";
break;
case "g";
$strBackgroundColor = "rgb(0,255,0)";
break;
case "b":
$strBackgroundColor = "rgb(0,0,255)";
break;
default:
$strBackgroundColor = "rgb(255,255,255)";
break;
}

?>
<html>
<head>
<title>Form</title>

</head>
<body style="background: <?php echo $strBackgroundColor; ?>;">

<? echo $strHeading; ?>

</body>
</html>
• The background color will be white if the user
has not chosen any favorite color in the form.
• This is done by using default to specify what
should happen if none of the above conditions
are met.
• But what if the user does not fill out his
name? Then it only says "Hello" in the title.
We will use an extra condition to change that.
<?php

$strUsername = $_POST["username"];

if ($strUsername != "") {
$strHeading = "<h1>Hello " . $_POST["username"] . "</h1>";
}
else {
$strHeading = "<h1>Hello stranger!</h1> ";
}

switch ($_POST["favoritecolor"]) {
case "r":
$strBackgroundColor = "rgb(255,0,0)";
break;
case "g";
$strBackgroundColor = "rgb(0,255,0)";
break;
case "b":
$strBackgroundColor = "rgb(0,0,255)";
break;
default:
$strBackgroundColor = "rgb(255,255,255)";
break;
}

?>

<html>

<head>

<title>Form</title>
</head>
<body style="background: <?php echo $strBackgroundColor; ?>;">

<? echo $strHeading; ?>

</body>
</html>
Example: contact form
• With your new knowledge of PHP and forms,
you are able to create a contact form using
the function mail, which has the following
syntax:
mail(to, subject, message);
• First, we need a simple HTML form:
• Next we need a PHP script to send the users
input:
<html>
<head>
<title>Contact form</title>
</head>
<body>

<h1>Contact form</h1>

<form method="post" action="handler.php">


<p>Subject:<br /><input type="text" name="subject" /></p>
<p>Message:<br /><textarea name="message"></textarea></p>
<input type="submit">
</form>

</body>
</html>
<html>
<head>
<title>Functions</title>
</head>
<body>

<?php
// Recipient (change to your e-mail address)
$strEmail = "[email protected]";

// Get user inputs


$strSubject = $_POST["subject"];
$strMessage = $_POST["message"];

mail($strEmail,$strSubject,$strMessage);
echo "Mail Sent.";
?>

</body>
</html>
• Please note that the example will only work if
you have access to a mail server.
• By default, this is not the case in XAMPP and
most free hosts.
• Also, some hosts may require that you include a
from header, which is done with an extra
parameter:
mail("[email protected]", "Test", "This is a
test mail", "From: [email protected]");
File Systems
Introduction
• With PHP, you can access the server's filesystem. This
allows you to manipulate folders and text files in PHP
scripts.
• For example, you can use PHP to read or write a text
file. Or you can list all files in a specified folder. There
are many possibilities and PHP can save you lots of
tedious work.
• filemtimeilemtime - Returns the time for which the
contents of a file was last edited (as UNIX timestamp -
see lesson fileatimeilemtime - Returns the time for
which the contents of a file was last edited (as UNIX
timestamp - see lesson fileatime - Returns the time
when a file was last accessed / opened (as a UNIX
timestamp - see lesson filesize - Returns the size of a
file in bytes.
Example
<html>

<head>
<title>Filesystem</title>
</head>
<body>

<?php

// Find and write properties


echo "<h1>file: myfirstphp.php</h1>";
echo "<p>Was last edited: " . date("r", filemtime(“qabu.php"));
echo "<p>Was last opened: " . date("r", fileatime(“qabu.php"));
echo "<p>Size: " . filesize(“qabu.php") . " bytes";

?>

</body>
</html>
Folders
• PHP also allows you to work with folders on
the server.
• opendirOpens a specified folder.
• readdirreaddirReturns the filename of the
next file in the open folder (cf. opendir)
• closedirCloses a specified folder.
<?php

// Opens the folder


$folder = opendir("../../myfiles/php/");

// Loop trough all files in the folder


while (($entry = readdir($folder)) != "") {
echo $entry . "<br />";
}

// Close folder
$folder = closedir($folder);

?>
Reading from a text file
• Text files can be extremely useful for storing
various kinds of data.
• They are not quite as flexible as real
databases, but text files typically don't require
as much memory.
• Moreover, text files are a plain and simple
format that works on most systems.
Opening the text file
• We use the fopen function to open a text file.
The syntax is as follows:
fopen(filename, mode)
• Filename - Name of the file to be opened.
• Mode - Mode can be set to "r" (reading), "w"
(writing) or "a" (appending). In this lesson, we
will only read from a file and, therefore, use
"r".
Example: opening a text file
<?php

// Open the text file


$f = fopen("unitednations.txt", "r");

// Close the text file


fclose($f);

?>
Reading a line
• With the function fgets, we can read a line
from the text file.
• This method reads until the first line break
(but not including the line break).
<html>

<head>
<title>Reading from text files</title>
</head>
<body>

<?php

$f = fopen("unitednations.txt", "r");

// Read line from the text file and write the contents to the client
echo fgets($f);

fclose($f);

?>

</body>
</html>
Reading all lines
<html>

<body>

<?php

$f = fopen("unitednations.txt", "r");

// Read line by line until end of file


while(!feof($f)) {
echo fgets($f) . "<br />";
}

fclose($f);

?>

</body>
</html>
Opening text file for writing
• In the same way as when reading from a text file,
the fopen function is used for writing, but this
time we set the mode to "w" (writing) or "a"
(appending).
• The difference between writing and appending is
where the 'cursor' is located - either at the
beginning or at the end of the text file.
• The examples in this lesson use an empty text file
called textfile.txt. But you can also create your
own text file if you like.
• First, let us try to open the text file for writing:
<?php

// Open the text file


$f = fopen("textfile.txt", "w");

// Close the text file


fclose($f);

?>
Writing a line
• To write a line, we must use the function
fwrite,
<?php

// Open the text file


$f = fopen("textfile.txt", "w");

// Write text line


fwrite($f, "PHP is fun!");

// Close the text file


fclose($f);

// Open file for reading, and read the line


$f = fopen("textfile.txt", "r");
echo fgets($f);

fclose($f);

?>
Databases
Introduction
• A database is a collection of information / data
that is organized so that it can easily be retrieved,
administrated and updated.
• Databases thereby enable the opportunity to
create dynamic websites with large amounts of
information. For example, all data on members of
HTML.net and all posts in the forums are stored
in databases.
• A database usually consists of one or more
tables.
• There are many different databases: MySQL,
MS Access, MS SQL Server, Oracle SQL Server
and many others. In this tutorial, we will use
the MySQL database.
• MySQL is the natural place to start when you
want to use databases in PHP.
• MySQL is already installed with xampp
Connection to database server
• First, you need to have access to the server
where your MySQL database is located. This is
done with the function mysql_connect with the
following syntax:
mysql_connect(server, username, password)
• First, you write the location of the database
(server), and then type in the username and
password. For xampp syntax is:
mysql_connect("localhost", "root", "") or die
(mysql_error());
Create databases and tables
• Using PHP
• Using PHPMyAdmin
Create a database and tables with
PHP
• When creating a database, the SQL query
CREATE DATABASE is used with the following
syntax:
CREATE DATABASE database name
• PHP script:
mysql_connect("mysql.myhost.com", "user",
"sesame") or die(mysql_error());
mysql_query("CREATE DATABASE mydatabase")
or die(mysql_error());
mysql_close();
Creating a table
• In the example, we will start by connecting to the
MySQL server. Next we use the function
mysql_select_db to select the database "people". Then
we create the table "persons" with 5 columns.
• at the "id" column, we first use INTat the "id" column,
we first use INT to specify that the column contains
numbers and then add AUTO_INCREMENT to
automatically increase the number and ensure a
unique ID for each row.
• At the end, we use PRIMARY KEY to set the "id" column
as the primary key. The primary key uniquely identifies
each record (/row) in the table, which becomes very
useful later when we update the database.
mysql_connect("mysql.myhost.com", "user", "sesame")
or die(mysql_error());
mysql_select_db("people") or die(mysql_error());

mysql_query("CREATE TABLE MyTable (


id INT AUTO_INCREMENT,
FirstName CHAR,
LastName CHAR,
Phone INT,
BirthDate DATE
PRIMARY KEY(id)
)") Or die(mysql_error());
mysql_close ();
Create database and tables with
phpMyAdmin
• Start by logging onto phpMyAdmin
• XAMPP, the address is
http://localhost/phpmyadmin/.
• When you are logged on, simply type a name
for the database and press the button
"Create":
• Then there will be a box titled "Create new
table in database", where you type the name
of the table and the number of columns and
press the button "Go":
• Then you can name the columns and set the
data type, etc., as in the SQL example above
Insert data into a database using SQL
INSERT INTO TableName(column1, column2, ...)
VALUES(value1, value2, ...)
•You can update multiple columns in the SQL
statement by specifying them in a
comma-separated list
•Eg
$strSQL = "INSERT INTO
people(FirstName,LastName,Phone,BirthDate)
VALUES('Gus','Goose','99887766 ','1964-04-20')";
mysql_query($strSQL) or die(mysql_error());
Save user input into a database
• Often you want to save user input in a
database
• this can be done by creating a form where the
values from the form fields can be inserted in
the SQL statement.
• Suppose you have a simple form like this:
<form action="insert.php" method="post">
<input type="text" name="FirstName" />
<input type="submit" value="Save" />

</form>
• The form submits to the file insert.php where
you can get the user's input by requesting the
form content.
• In this particular example, an SQL statement
could look like this:
strSQL = "INSERT INTO people(FirstName)
values('" . $_POST["FirstName"] . "')"
Retrieving data from a database
• To retrieve data from a database, you use
queries. An example of a query could be: "get
all data from the table 'people' sorted
alphabetically" or "get names from the table
'people'".
SELECT * FROM people
• All other SQL selection options can be used
Deleting a record
<?php
// Connect to database server
mysql_connect("mysql.myhost.com", "user", "sesame") or die
(mysql_error ());

// Select database
mysql_select_db("mydatabase") or die(mysql_error());

// The SQL statement that deletes the record


$strSQL = "DELETE FROM people WHERE id = 24";
mysql_query($strSQL);

// Close the database connection


mysql_close();
?>
Updating data
<?php
// Connect to database server
mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());

// Select database
mysql_select_db("mydatabase") or die(mysql_error());

// The SQL statement is built


$strSQL = "Update people set ";
$strSQL = $strSQL . "FirstName= 'D.', ";
$strSQL = $strSQL . "Phone= '44444444' ";

$strSQL = $strSQL . "Where id = 2";

// The SQL statement is executed


mysql_query($strSQL);

// Close the database connection


mysql_close();
?>
• Use any html tutorial like
http://html.net/tutorials for practice

You might also like