0% found this document useful (0 votes)
67 views

The PHP Hypertext Pre

PHP is a server-side scripting language that allows developers to create dynamic content and interact with databases. It can be embedded into HTML and is used to manage dynamic web page content, track sessions, and build e-commerce sites. Some key uses of PHP include performing system functions like file manipulation, handling forms, modifying database elements, setting cookies, and restricting page access. PHP scripts are executed on the server and the output is returned to the browser as HTML. PHP files use the .php extension and contain text, HTML tags, and PHP scripts executed by the PHP interpreter.

Uploaded by

qwerty
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

The PHP Hypertext Pre

PHP is a server-side scripting language that allows developers to create dynamic content and interact with databases. It can be embedded into HTML and is used to manage dynamic web page content, track sessions, and build e-commerce sites. Some key uses of PHP include performing system functions like file manipulation, handling forms, modifying database elements, setting cookies, and restricting page access. PHP scripts are executed on the server and the output is returned to the browser as HTML. PHP files use the .php extension and contain text, HTML tags, and PHP scripts executed by the PHP interpreter.

Uploaded by

qwerty
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

PHP HYPERTEXT PRE-PROCESSOR (PHP)

The PHP Hypertext Pre-processor (PHP) is a programming language that allows web
developers to create dynamic content that interacts with databases. PHP is basically used
for developing web based software applications.
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP is a server side scripting language that is embedded in HTML. It is used to manage
dynamic content, databases, session tracking, even build entire e-commerce sites.
It is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server

Common uses of PHP:


PHP performs system functions, i.e. from files on a system it can create, open,
read, write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, thru email
you can send data, return data to the user.
You add, delete, modify elements within your database thru PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.

PHP is a powerful server-side scripting language for creating dynamic and interactive
websites.
PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's
ASP. PHP is perfectly suited for Web development and can be embedded directly into the
HTML code.
PHP file
A PHP file may contain text, HTML tags and scripts. Scripts in a PHP file are
executed on the server.
PHP files are returned to the browser as plain HTML
PHP files have a file extension of ".php"
What You Should Already Know
Before you continue you should have a basic understanding of the following:
HTML / XHTML
Some scripting knowledge

Where to Start?
Install an Apache server on a Windows or Linux machine

Install PHP on a Windows or Linux machine


Install MySQL on a Windows or Linux machine
Basic PHP Syntax
A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting
block can be placed anywhere in the document.
In other words the PHP code is enclosed within special start and end tags which denote
the start and end of the PHP script, these tags are. When a PHP file is requested by a Web
browser a PHP interpreter parses through the file ignoring everything and anything until a
special start tag is encountered. The PHP interpreter will then from that point on interpret
the code found replacing the PHP script with the output it generates at that point in the
document until a special close tag is encountered. At which time the interpreter continues
parsing the document
<?php
.php code..
?>

PHP - Echo
As you saw in the previous lesson, the PHP function echo is a means of outputting text to
the web browser. Throughout your PHP career you will be using the echo function more
than any other

Example One
<html>
<head>
<title>First Example<title>
<body>
<?php

echo Hello World;


?>
</body>
</html>
Example Two
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Example Three
<?php
$myString = "Hello!";
echo $myString;
echo "<h5>I love using PHP!</h5>";
?>

Within a document you can embed PHP start and end tags and code at many
points, consider the following example:
<?php
echo '<p>This is PHP script generated.</p>';
?>
<p>This is not.</p>
<?php

echo '<p>This is also PHP script generated.</p>';


?>
The Semicolon!
PHP requires instructions to be terminated with a semicolon at the end of
each statement.
<?php
echo '<p>Hello, World!</p>';
echo '<p>Hello, World!</p>';
?>
Example Four
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
echo "Hello World! ";
?>
</body>
</html>

Commenting PHP Code:


A comment is the portion of a program that exists only for the human reader
and stripped out before displaying the programs result. There are two
commenting formats in PHP:
PHP supports a number of different styles of comments
// this is a single line comment

/* this comment is an example of


a multi-line comment */
<?php
/* This script will display the text Hello, World! twice on

separate lines of the web browser */


echo '<p>Hello, World!</p>'; // This is the first Hello, World!
echo '<p>Hello, World!</p>'; // This is the second.
?>

PHP - Variables
Variables can be thought of as containers which hold data. The data held by
a variable can change during the execution of a PHP script, hence the name
variable.
A variable is a means of storing a value, such as text string "Hello World!"
or the integer value 4.
Variables in PHP are represented by a $ symbol followed by the name of
the variable.
$var_name = value;
$name = Simon;
NB: PHP variable names are case sensitive. Therefore the variable $name is a different
variable to $Name. Be careful!
PHP Variable Naming Conventions
There are a set of rules which need to be considered in naming your variables.
A valid variable name can start with a letter or an underscore character, followed by any
number of letters, numbers or underscores

The following script illustrates some example valid variables:


<?php
$var = 'Elizabeth';
$_var = 56;
$Var = 'Hall';
echo <p>$var $Var $_var</p>;
?>

The following variables are all invalid:


var = Simon; // Invalid - does not start with a $ symbol
$2var = Simon; // Invalid name starts with a number

PHP is a Loosely Typed Language


PHP automatically converts the variable to the correct data type, depending
on how they are set.
In a strongly typed programming language, you have to declare (define) the
type and name of the variable before using it.
PHP Variable Types
Variable data is stored in the computers memory but the computer needs to know in what
format the data should be stored as different types of data take up different amounts of
space. The format of a piece of data is known as its data type and PHP supports eight
primitive types. PHP has a total of eight data types which we use to construct our
variables:

Integers: are whole numbers, without a decimal point, like 4195.


Doubles: are floating-point numbers, like 3.14159 or 49.1.
Booleans: have only two possible values either true or false.
NULL: is a special type that only has one value: NULL.
Strings: are sequences of characters, like 'PHP supports string operations.'
Arrays: are named and indexed collections of other values.
Objects: are instances of programmer-defined classes, which can package up
both other kinds of values and functions that are specific to the class.
Resources: are special variables that hold references to resources external to PHP
(such as database connections).

Therefore, the following illustrates variable names:


$strName = 'Elizabeth';
$intAge = 34;
$booAnswer = True;
$intNumber = 5;
$intAnotherNumber = -5;
$floNumber = 1.234;

Strings
A string is a series of characters. We have used strings in our previous PHP examples but
it is now time to explain that PHP has three different ways in which strings can be
specified.
<?php
$strName = 'Elizabeth';
echo '<p>';
echo $strName;
echo '</p>';
?>

Backslash (\) character


If we were to simply enclose this in single quotes the PHP interpreter would not know
which single quote indicated the end of the string:
'Hello Im Simon'
To overcome this problem PHP uses a backslash (\) character known as escape to allow
us to include single quotations within our strings. Therefore the above string would look
like this:
'Hello I\m Simon'
NB.
Strings in PHP can be very large. You dont need to worry about using long strings!

String Operators
PHP supports two string operators.

<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
$Named = "Elizabeth";
$age=45;
echo "My name is ". $Named. " and I'm ".$age." old";
?>
</body>
</html>
</body>
</html>

<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
$strNamed = "Elizabeth";
$intage=45;
echo "My name is ". $strNamed. " and I'm ".$intage." old";
?>
</body>
</html>
</body>
</html>

<?php
$strFirstname = "Simon";
$strSurname = "Stobart";

$strFullname = $strFirstname . $strSurname;


echo "<p>$strFirstname joined with $strSurname is $strFullname</p>";
$strFullname = $strFirstname . " " . $strSurname;
echo "<p>$strFirstname joined with $strSurname with a space is
$strFullname</p>";
$strFullname = $strFirstname;
$strFullname .= " ";
$strFullname .= $strSurname;
echo "<p>$strFirstname joined with $strSurname with a space is
$strFullname</p>";
?>

PHP Decision Making (Sequential Execution)


if...else statement - use this statement if you want to execute a set of code when a
condition is true and another if the condition is not true
elseif statement - is used with the if...else statement to execute a set of code
if one of several condition are true
switch statement - is used if you want to select one of many blocks of code to be
executed, use the Switch statement. The switch statement is used to avoid long blocks of
if..elseif..else code.

The If...Else Statement


If you want to execute some code if a condition is true and another code if a condition is
false, use the if....else statement.
Syntax

if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

<?php
$intA = 5;
$intB = 3;
if ($intA > $intB)
echo "<p>$intA is greater than $intB</p>";
?>
<?php
$strColour = "green";
if ($strColour == "green")
echo "<p>The colour is green</p>";
if ($strColour == "green")
echo "<p>Green is a nice colour</p>";
if ($strColour == "green")
echo "<p>We have the colour of grass</p>";
?>

Brace characters may be used to ({ }) to group all statements that you wish to
conditionally execute into a statement group, for example:
<?php
$strColour = "green";
if ($strColour == "green") {
echo "<p>The colour is green</p>";
echo "<p>Green is a nice colour</p>";
echo "<p>We have the colour of grass</p>";
}
?>

Braces can be formatted so that they appear like the example above:
If ( expression ) {

}
Alternatively they can appear on separate lines:
If ( expression )
{

The if else construct


Sometimes you may wish to execute a certain statement if a condition is met and another
statement if it is not. This is accomplished using the else statement which extends the if
construct.
The structure of the if - else construct is as follows:
if ( expression )
statement to be executed if condition is true
else
statement to be executed if condition is false
<?php
$intA = 5;
$intB = 3;
if ($intA > $intB)
echo "<p>$intA is greater than $intB</p>";
else
echo "<p>$intA is less than or equal to $intB</p>";
?>
<?php
php
$strColour = "blue";
if ($strColour == "green") {
echo "<p>The colour is green</p>";
echo "<p>Green is a nice colour</p>";
echo "<p>We have the colour of grass</p>";
}
else {
echo "<p>We don't know what colour we have</p>";
echo "<p>Other than it is not green</p>";
}
?>

The if elseif construct


The elseif construct is a combination of if and else. It operates in a similar way to the else
construct, in that it extends the if construct to execute a different statement if the if
expression is evaluated to false.
if ( expression )
statement to be executed if condition is true
elseif ( expression )
statement to be executed if elseif condition is true
if ( expression )
statement to be executed if condition is true

elseif ( expression )
statement to be executed if elseif condition is true
else
<?php
$intNumber1 = 100;
$intNumber2 = 80;
if ($intNumber1 > $intNumber2)
{
echo "<p>$intNumber1 is larger than $intNumber2</p>";
}
elseif ($intNumber1 == $intNumber2)
{
echo "<p>$intNumber1 is equal to $intNumber2</p>";
}
else
{
echo "<p>$intNumber1 is smaller than $intNumber2</p>";
}
?>

switch construct
The switch construct is similar to a series of if statements acting on the same conditional
expression. The switch construct is used when you wish to compare a variable against a
number of different values and execute different code statements depending on the
variables value.
The case construct consists of a switch component in which an expression is evaluated.
The result of the expression is then compared in turn to a list of case statements. The first
case value which matches to the expression will determine which associated statements
are executed
The syntax of the switch statement is:
switch ( expression )
{
case constant expression : statement
case constant expression : statement
...
default : statement
}
<?php
$strName = "Elizabeth";
switch ($strName) {
case "Simon":
echo "<p>Hello Simon</p>";
case "Elizabeth":

echo "<p>Hello Elizabeth</p>";


case "Hayley":
echo "<p>Hello Hayley</p>";
case "Alan":
echo "<p>Hello Alan</p>";
}
?>

Switch and break


The break statement can be used to end the current execution of a switch statement.
<?php
$strName = "Elizabeth";
switch ($strName)
{
case "Simon":
echo "<p>Hello Simon</p>";
break;
case "Elizabeth":
echo "<p>Hello Elizabeth</p>";
break;
case "Hayley":
echo "<p>Hello Hayley</p>";
break;
case "Alan":
echo "<p>Hello Alan</p>";
}
?>

<?php
$intTotal = 3;
switch ($intTotal)
{
case 0:
case 1:
case 2:
case 3:
case 4:
echo "<p>$intTotal is less than or equal to four!</p>";
break;
case 5:
echo "<p>$intTotal is greater than four!</p>";
}
?>

<?php
$intTotal = 6;
switch ($intTotal) {
case 0:
case 1:
case 2:
case 3:
case 4:
echo "<p>$intTotal is less than or equal to four!</p>";
break;
case 5:
echo "<p>$intTotal is equal to five!</p>";
break;
default:
echo "<p>$intTotal is greater than five!</p>";
}
?>

PHP Loops
While loops
while ( expression )
{
statement

}
<?php
$intCount = 1;
while ($intCount <= 10)
{
echo "<p>Iteration $intCount</p>";
$intCount++;
}
?>

Do while loops
do
{
statement
statement


}
while ( expression );

<?php
$intCount = 1;
Do
{
echo "<p>Iteration $intCount</p>";
$intCount++;
} while ($intCount <= 10);
?>
<?php
$intCount = 1;
Do
{
echo "<p>Iteration $intCount</p>";
$intCount++;
} while ($intCount < 1);
?>

For loop
There are three expressions incorporated into the for construct.
The syntax for the loop is:
for (expression; expression; expression)
{
statement
statement

}
<?php
for($intCount = 1; $intCount <= 10; $intCount++)
echo "<p>Iteration $intCount</p>";
?>

foreach loop
PHP supports a special loop construct for accessing the contents of arrays
Used in Array Examples

Arrays
An array in PHP is actually an ordered map, where a map is a type which maps values to
keys. Because PHP stores its arrays as maps it means that they can be used for a whole
variety of different data structures such as lists, trees, stacks etc. Arrays are used to
collect together data, such as peoples names and perform operations on this data as
easily as possible. PHP supports both single and multi-dimensional arrays, but for now
lets look at creating a very simple array.
Arrays are created using the array construct:
theArray = array (arrayItem1, arrayItem2, );
Example
$arrColours = array (Red, Green, Blue, Yellow, White);

This creates an array called $arrColours which contains 5 elements storing various
colours. We can refer to the elements within the array by using a subscript to the array
name. Because the index defaults to numbering the array index from 0 to in this case to 4
then we can access the first element of the array by the following statement:

$arrColours[0];
and the last element of the array by:
$arrColours[4];
Example
<?php
$arrColours = array ("Red", "Green", "Blue", "Yellow", "White");
for($intCount=0;$intCount<5;$intCount++)
echo "<p>" . $arrColours[$intCount] . "</p>";
?>

Array Output

An Array with a Key


We can create an array and specify our own index key at the same time.
$arrColours = array (0=>Red, 1=>Green, 2=>Blue, 3=>Yellow,
4=>White);
A key index can be specified using the operator =>. In the above example the index has
been specified exactly as the default index would, a numerical index starting from 0 and
incremented by one each time. But what if we put the index items in a different order and
even missed out an index number, for example:
$arrColours = array (0=>Red, 2=>Green, 3=>Blue, 5=>, 1=>Yellow,
4=>White);

In the above example the index has not been created in numerical order and in addition a
blank index key, number 5 has been included. If we use the above array with a slightly
modified version of our simple for loop example before we can see what is displayed
when we cycle through the array:

<?php
$arrColours = array (0=>"Red", 2=>"Green", 3=>"Blue", 5=>"", 1=>"Yellow",
4=>"White");
for($intCount=0;$intCount<6;$intCount++)
echo "<p>$intCount " . $arrColours[$intCount] . "</p>";
?>

The output from the script is shown in Figure below

Foreach
PHP includes a loop construct specifically designed for iterating through arrays. This
loop construct is known as the foreach loop and there are two syntaxes. The first form is:
foreach (array as value) statement
The foreach loop will iterate through the array provided by array. The value in the current
index is assigned to value. The array index is then incremented by one so the next
iteration of the loop will access the next element of the array. An example of this loop has
been included in the following script that is a rewrite of the previous one:

<?php
$arrColours = array (0=>"Red", 2=>"Green", 3=>"Blue", 5=>"", 1=>"Yellow",
4=>"White");
$intCount = 0;
foreach($arrColours as $strColour)
echo "<p>" . $intCount++ . " $strColour</p>";
?>

Note that the output of the colours is also in the order in which they were declared,
not in the numerical index order, as with the for loop.

This foreach statement is similar to the previous example but in addition assigns the value
of the current elements index to the key. This is shown in the following script:
<?php
$arrColours = array (0=>"Red", 2=>"Green", 3=>"Blue", 5=>"", 1=>"Yellow",
4=>"White");
foreach($arrColours as $intKey=>$strColour)
echo "<p>$intKey $strColour</p>";
?>

Arrays and non numerical keys


Arrays dont have to have a numerical key, for example:
$arrColours = array (red=>Red, green=>Green, blue=>Blue,
yellow=>Yellow, white=>White);

The following script illustrates the use of such an array:


<?php
$arrColours = array ("red"=>"Red", "green"=>"Green", "blue"=>"Blue",
"yellow"=>"Yellow", "white"=>"White");
foreach($arrColours as $strKey=>$strColour)
echo "<p>$strKey $strColour</p>";
?>

PHP Functions
The real power of PHP comes from its functions.
In PHP - there are more than 700 built-in functions available.
Create a PHP Function
A function is a block of code that can be executed whenever we need it.
Creating PHP functions:
function functioname()
{
Code to be executed
}

<html>
<body>
<?php
function writeMyName()
{
echo "Kai Jim Refsnes";
}
writeMyName();
?>
</body>
</html>

PHP Functions - Adding parameters

To add more functionality to a function, we can add parameters. The parameters are
specified inside the parentheses.
<html>
<body>
<?php
function writeMyName($fname)
{
echo $fname . " Refsnes.<br />";
}
echo "My name is ";
writeMyName("Kai Jim");
echo "My name is ";
writeMyName("Hege");
echo "My name is ";
writeMyName("Stale");
?>
</body>
</html>
The output of the code above will be:

My name is Kai Jim Refsnes.


My name is Hege Refsnes.
My name is Stale Refsnes.

<html>
<body>
<?php
function writeMyName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br />";
}
echo "My name is ";
writeMyName("Kai Jim",".");
echo "My name is ";
writeMyName("Hege","!");
echo "My name is ";
writeMyName("Stle","...");
?>
</body>
</html>

The output of the code above will be:

My name is Kai Jim Refsnes.


My name is Hege Refsnes!
My name is Stle Refsnes...

PHP Functions - Return values


Functions can also be used to return values.

Example

<html>
<body>
<?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16)
?>
</body>
</html>

PHP and Form Interaction


PHP can use forms to allow a script to interact with the user.
Using forms to interact with PHP we start by creating an XHTML web form
PHP Forms and User Input
The PHP $_GET and $_POST variables are used to retrieve information from
forms, like
user input.
PHP $_GET
The $_GET variable is used to collect values from a form with method="get".
The $_GET Variable
The $_GET variable is an array of variable names and values sent by the HTTP GET
method.
The $_GET variable is used to collect values from a form with method="get".
Information sent from a form with the GET method is visible to everyone (it will be
displayed in the browser's address bar) and it has limits on the amount of information to
send (max. 100 characters).

Example

<form action="welcome.php" method="get">


Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
When the user clicks the "Submit" button, the URL sent could look something like this:
http://www.w3schools.com/welcome.php?name=Peter&age=37
The "welcome.php" file can now use the $_GET variable to catch the form data (notice
that the names of the form fields will automatically be the ID keys in the $_GET array):
Welcome <?php echo $_GET["name"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!

Note: When using the $_GET variable all variable names and values are displayed in the
URL. So this method should not be used when sending passwords or other sensitive
information.
Note: The HTTP GET method is not suitable on large variable values; the value cannot
exceed 100 characters.

PHP $_POST
The $_POST variable is used to collect values from a form with method="post".

The $_POST variable is an array of variable names and values sent by the HTTP POST
method.
The $_POST variable is used to collect values from a form with method="post".
Information sent from a form with the POST method is invisible to others and has no
limits on the amount of information to send.
Note: Variables sent with HTTP POST are not shown in the URL
Note: Variables have no length limit
The $_REQUEST Variable
The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and
$_COOKIE.
The PHP $_REQUEST variable can be used to get the result from form data sent with
both the GET and POST methods.
Example
Welcome <?php echo $_REQUEST["name"]; ?>.<br />
You are <?php echo $_REQUEST["age"]; ?> years old!

PHP Form Handling


The most important thing to notice when dealing with HTML forms and PHP is that any
form element in an HTML page will automatically be available to your PHP scripts. i.e
create the PHP script which the XHTML form invokes.
The example1 HTML page below contains two input fields and a submit button. When
the user fills
in this form and click on the submit button, the form data is sent to the "welcome.php"
file.
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
welcome.php" file
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>

Accessing form data is essentially very easy. When a form is created an associated array
of variables is created. This array is called $_POST. Each HTML form element that has a
unique name is stored in the array and can be accessed by the PHP script. The $_POST
syntax is as follows:
$_POST["name"];
name is the name of the form value we wish to access. In our example we have assigned
the contents of each of our form fields into variables of the same name:
$strFirstname = $_POST["strFirstname"];

$strSurname = $_POST["strSurname"];
$strUsername = $_POST["strUsername"];
$strPassword = $_POST["strPassword"];
The values of these variables are then finally displayed using a couple of echo
statements.
The example2 HTML page below contains several input fields and a submit button. When the user
fills in this form and click on the submit button, the form data is sent to the "example1.php" file.

<HTML>
<BODY>
<h2>Please enter your personal details:</h2>
<form action="example1.php" method="post">
Firstname<input type="text" name="strFirstname"/><BR>
Surname<input type="text" name="strSurname" /><BR>
Username<input type="text" name="strUsername" /><BR>
Password<input type="password" name="strPassword"
/><BR>
<input type="submit"/>
</p>
</form>
</BODY>
</HTML>
<HTML>
<BODY>
<?php
$strFirstname = $_POST["strFirstname"];
$strSurname = $_POST["strSurname"];
$strUsername = $_POST["strUsername"];
$strPassword = $_POST["strPassword"];
echo "<p>Greetings $strFirstname $strSurname</p>";
echo "<p>Your username is $strUsername and your password
is $strPassword</p>";
?>
</HTML>
</BODY>

Combining PHP and Forms


What we are going to do is to combine our XHTML form and PHP script together in a
single document. When the form submit button is clicked the form will invoke itself and
process the PHP script within it.
<HTML>
<BODY>

<h2>Please enter your personal details:</h2>


<form action='example3.php' method='post'>
<p>
<label for="strFirstname">Firstname: </label>
<input type="text" name="strFirstname" id="strFirstname"/>
</p><p>
<label for="strSurname">Surname: </label>
<input type="text" name="strSurname" id="strSurname"/>
</p><p>
<label for="strUsername">Username: </label>
<input type="text" name="strUsername" id="strUsername"/>
</p><p>
<label for="strPassword">Password: </label>
<input type="password" name="strPassword" id="strPassword"/>
</p><p>
<input type="submit"/>
</p>
</form>
<?php
// File: example3-2.php
$strFirstname = $_POST["strFirstname"];
$strSurname = $_POST["strSurname"];
$strUsername = $_POST["strUsername"];
$strPassword = $_POST["strPassword"];
echo "<p>Greetings $strFirstname $strSurname</p>";
echo "<p>Your username is $strUsername and your password is
$strPassword</p>";
?>
</BODY>
</HTML>
When the page is viewed for the first time the output from the PHP statements is
visible and as no form data has been sent yet the variables contain no values, hence
the strange looking output displayed after the form.
This is not a see that when problem after the form is submitted but the first time the
page is loaded the form variables contain no data and this results in the display of an
incomplete message. What we need is a means of determining if the form data was
submitted or not, and here it is:

<HTML>
<BODY>
<h2>Please enter your personal details:</h2>
<form action='example6.php' method='post'>
<p>
<label for="strFirstname">Firstname: </label>

<input type="text" name="strFirstname" id="strFirstname"/>


</p><p>
<label for="strSurname">Surname: </label>
<input type="text" name="strSurname" id="strSurname"/>
</p><p>
<label for="strUsername">Username: </label>
<input type="text" name="strUsername" id="strUsername"/>
</p><p>
<label for="strPassword">Password: </label>
<input type="password" name="strPassword" id="strPassword"/>
</p><p>
<input type="submit" name="submit"/>
</p>
</form>
<?php
if ($_POST["submit"])
{
$strFirstname = $_POST["strFirstname"];
$strSurname = $_POST["strSurname"];
$strUsername = $_POST["strUsername"];
$strPassword = $_POST["strPassword"];
echo "<p>Greetings $strFirstname $strSurname</p>";
echo "<p>Your username is $strUsername and your password is
$strPassword</p>";
}
?>
</BODY>
</HTML>

PHP MySQL Introduction


A database is a structured collection of data. Databases occurred in the real world before
computers were invented. Examples of real world databases include:
TV times guide
Filing cabinet of documents
Telephone book

What is MySQL?
MySQL is a database. A database defines a structure for storing information.
Relational Database
In relational database systems such as MySQL data is organized into tables

Database Tables
A database most often contains one or more tables. Each table has a name (e.g.
"Customers" or "Orders"). Each table contains records (rows) with dat

We see that it contains a table called Customers. This table consists of three column fields of
data entitled Title, Surname and Firstname. The data is inserted into each of these fields
forming a number of record rows within the table.
Queries

Database queries
A query is a question or a request.
With MySQL, we can query a database for specific information and have a recordset
returned.
Connecting to a MySQL DBMS
PHP MySQL Connect to a Database
The free MySQL Database is very often used with PHP
Connecting to a MySQL DBMS
In order for a PHP script to access a database we need to form a connection from the script to
the database management system (DBMS). To do this we use the mysql_connect() function

resourceId mysql_connect(server, username, password);


or

mysql_connect(servername,username,password);
The mysql_connect() function requires three parameters. The first is the name of the server,
the second is your username and the third your password.

If you are developing on your own standalone computer the format of this function may
look like this with the value of server set to be localhost, the username as root and
whatever password you have set:

$dbLocalhost = mysql_connect("localhost", "root", "password")


Select the database
Having created a link to the DBMS we wish to access the next stage is to select the database
that we wish to use. This is done using the function mysql_select_db() which allows us to
specify which database at the location defined in the mysql_connect() function we wish to
access.
bool mysql_select_db(databasename, resourceId)
The mysql_select_db() function requires two parameters. The first is the name of the
database you wish to access and the second is the resourceId which was returned from
invoking the previous mysql_connect() function. The function returns true if the database
selection worked or false if not.
mysql_select_db(glassesrus, $dbLocalhost)

The die() function


The die() function is combined with an or operator in order to stop execution of the script
if the previous database connection could not be formed, it looks like this:

die (Error Message)


Function die() has a single parameter which is a message which is displayed before
execution is stopped.
It is common practice to combine the use of function die() with that of function.
mysql_error() which returns the text of the error message from the previous MySQL
operation
Combining function die() and function mysql_error() looks like this:
The mysql_error() function requires no parameters and returns an error message string.
die("Could not connect: " . mysql_error())
Combining the die() function along with the mysql_connect() function requires us to use
the or construct like this:
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
The above code fragment should now be read as form a mysql connection to localhost
and if this doesnt work stop the script
We are now ready to form these functions together into our first PHP script and here it is:

<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
echo "<h1>Connected To Database</h1>";
?>
The above script opens a connection to the DBMS server and then attempts to select
database glassesrus.
Reading a Database
The next step in linking PHP to a database is to get it to send a Structured Query
Language (SQL) statement to the database in order to begin to retrieve data records.
To do this we need to introduce a new function that of mysql_query()
resourceRecords mysql_query (query, resourceId);

Function mysql_query() requires two parameters, the first is an SQL query string and the
second is the database resource identifier returned from the mysql_connect() function.
Example
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
Adding this function into our script gives us.

<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
echo "<h1>Connected To Database</h1>";
?>
Now the mysql_query() function returns us a resource pointer to all the records which
match the SQL statement we supplied. This could be zero, one or many records. What we
need is a function which will return the contents of one record cell from the record set.
This function is called mysql_result():
fielddata mysql_result (resourceRecords, row, field);

The mysql_query() function requires three parameters. The first is the resource pointer to
the records returned by the mysql_query() function. The second is the number
indicating which record to return, with 0 being the first record, 1 the second and so on.
The third parameter is the name of the database field to return. The function returns the
data stored in the field. Here is an example of the function:
$strSurname = mysql_result($dbRecords, 0, surname);
Adding this function into our script gives us.

<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
$strSurname = mysql_result($dbRecords, 0, "Surname");
echo "<p>$strSurname</p>";
?>

Viewing a Whole Record


<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
$strSurname = mysql_result($dbRecords, 0, "Surname");
$strTitle = mysql_result($dbRecords, 0, "Title");
$strFirstname = mysql_result($dbRecords, 0, "Firstname");
$intId = mysql_result($dbRecords, 0, "Id");
echo "<p>$intId $strTitle $strFirstname $strSurname</p>";
?>
Viewing All Returned Records
To display all the records which are returned from mysql_query() we need to introduce a
new function called mysql_fetch_row():
array mysql_fetch_row(resourceRecords);

The function requires a single parameter which is the resource identifier returned from
the mysql_result() function. It returns an array containing the database record. When
this new function is combined with a loop construct we can access and display all of the
records returned.
<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
while ($arrRecord = mysql_fetch_row($dbRecords))
{
echo "<p>" . $arrRecord[0] . " ";
echo $arrRecord[1] . " ";
echo $arrRecord[2] . " ";
echo $arrRecord[3] . "</p>";
}
?>

This function returns a single database record and stores this in the array $arrRecord.
When the last record has been returned mysql_fetch_row() returns false and the loop
will stop iterating.
Within the loop a number of echo statements are used to display the fields. The fields are
stored within the $arrRecord array and are accessed through each array element, 0, 1, 2
and 3.
mysql_fetch_array()
The function mysql_fetch_array() is an extended version of function mysql_fetch_row():
Like the mysql_fetch_row() function the mysql_fetch_array() function requires a single
parameter which is the resource identifier returned from the mysql_result() function. It
returns an array containing the database record.
The one thing that does differ from the mysql_fetch_row() function is that we can refer to
the database fields by name.

<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
{
echo "<p>" . $arrRecords["Id"] . " ";
echo $arrRecords["Title"] . " ";
echo $arrRecords["Surname"] . " ";
echo $arrRecords["Firstname"] . "</p>";
}
?>

Inserting New Records


We can create new database records. To do this we need a new SQL statement, the
INSERT INTO query which looks like this:
INSERT INTO table (field1, field2, ) VALUES ('value1', 'value2', )

<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbProdRecords = mysql_query("INSERT INTO products VALUES ('', 'Beer
Mug', '600 ml Beer Mug', '100', '5.99')", $dbLocalhost)
or die("Problem writing to table: " . mysql_error());
?>

The above script invokes a mysql_query() function with the SQL statement:
INSERT INTO products VALUES ('', 'Beer Mug', '600 ml Beer Mug', '100', '5.99')
This SQL statement creates a new data record in the products table.

Deleting Records
We can delete records from tables using the mysql_query() function using the DELETE
FROM query:
DELETE FROM table WHERE field=value
The DELETE FROM query requires the name of the database table to be provided as
well as the field and its value which we are looking to delete.
DELETE FROM customers WHERE Id='3'

<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbCustRecords = mysql_query("DELETE FROM customers WHERE Id='3'",
$dbLocalhost)
or die("Problem writing to table: " . mysql_error());
?>

Amending Records
The SQL UPDATE query can be used to modify the contents of an existing database
record.

UPDATE table SET field1='value1', field2='value2' WHERE field='value'


The UPDATE statement requires you to specify the name of the table in which to update,
provide a list of the fields and their new updated values and finally indicate which
records should be updated with these values.
<?php
$dbLocalhost = mysql_connect("localhost", "root", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbCustRecords = mysql_query("UPDATE products SET Description='250 ml Tall
Glass' WHERE Id='6'", $dbLocalhost)
or die("Problem updating table: " . mysql_error());
?>

You might also like