LetMeRead Net PHP and MySQL PHP Programming and MySQL for Beginners
LetMeRead Net PHP and MySQL PHP Programming and MySQL for Beginners
P H P P R O G R A M M I N G A N D M Y S Q L F O R B E G I N N E R S
Claudia Alves
1st edition
2020
---
introduction
PHP - what is it anyway?
Static and dynamic websites
1.3 Applications for PHP
1.4 SQL databases for internet applications
Chapter 2
Preparatory measures for programming with PHP
2.1 HTML
2.2 Web server software for running a PHP program
2.3 Install a suitable text editor
Chapter 3
The first program with PHP design
3.1 Make PHP scripts recognizable in the text
3.2 Write the first program
3.3 Getting the program up and running
3.4 Exercise: Writing a simple program in PHP
Chapter 4
Combine PHP and HTML
4.1 Outputting HTML code with PHP
4.2 Integrating PHP scripts into an HTML page
Chapter 5
Variables: an important element of PHP
programming
5.1 Capture text with one variable
5.2 Save numbers as variables
5.3 Boolean variables
5.4 Operations with variables
5.5 Arrays: composite variables
5.6 Exercise: dealing with variables
Chapter 6
Decisions through if queries
6.1 The structure of an if-query
6.2 Use different comparison operators
6.3 Integrating logical operators into the query
6.4 else and elseif
6.5 Exercise: Create queries yourself
Chapter 7
Extending the functionality of a program through
loops
7.1 Head-controlled loops: while and for
7.2 Foot-controlled loop: do while
7.3 foreach loops for working with arrays
7.4 Exercise: Designing programs with loops
Chapter 8
Functions in PHP
8.1 The structure of a function in PHP
8.2 Return values of the functions
8.3 Integrating a function in the PHP program
8.4 Using functions from the PHP library
Chapter 9
Object-oriented programming: classes, objects and
methods
9.3 Methods for working with objects
9.4 Exercise: Using classes, objects and methods
Chapter 10
Files for storing data
10.1 Reading in data from a file
10.2 Save data in a file
10.3 Pay attention to the file rights
10.4 Exercise: Using files for data storage
Chapter 11
Databases: The efficient alternative for data storage
11.1 What is a database?
11.2 The structure of databases
11.3 MySQL: important management system for databases
11.4 SQL: the database language for working with MySQL
Chapter 12
Basic operations for dealing with MySQL databases
12.1 DDL, DCL and DML: three types of SQL commands
12.2 Create databases and tables
12.3 Enter data
12.4 Change data
12.5 Delete data
12.6 Manage access rights
12.7 Exercise: Creating a table in MySQL
Chapter 13
Other important SQL functions
13.1 Select subsets of the data records
13.2 Determine the number of entries
13.3 Adding up values stored in cells
13.4 Exercise: Retrieving information from an inventory
Chapter 14
Integrate SQL database in PHP
14.1 Connect the PHP program to a database
14.2 Fill the database
14.3 Delete or change entries
14.4 Query data
14.5 Exercise: Editing databases with PHP
Chapter 15
Application example: recording customer data via the
Internet
15.1 Customer data via a form field query generated with
PHP
15.4 Displaying customer data with a PHP program
Chapter 16
PHP and Cookies: Recognizing Visitors and Saving
Information
16.1 What is a cookie?
16.2 Set a cookie
Chapter 16
PHP and cookies: Recognize visitors and save
information
16.1 What is a cookie?
16.2 Set a cookie
16.3 Evaluate information from the cookie
16.6 Exercise: Create cookies yourself
17.5 Exercise: Sending emails and designing PDFs
introduction
PHP and SQL are two important elements of many Internet applications. PHP
is one of the programming languages most commonly used for creating
websites. It is ideal for creating dynamic content. These allow the pages to be
individually adapted to the user or to the context. The data used to create the
content is usually stored in a database. This offers a very efficient and well-
structured system for data storage. A database language is used to set up a
database, to store individual data in it or to call it up. The SQL language is
particularly popular for web applications. The contents of countless web
applications are stored in SQL databases. PHP is characterized, among other
things, by a broad database support. Countless functions are available,
especially for SQL databases. It is precisely this good interaction between
programming language and database connection that makes PHP a very
powerful tool for many web applications. As a result, PHP and SQL play a
prominent role in the design of Internet pages. This book provides an
introduction to the use of PHP and SQL. The readers first learn to write
simple programs in PHP. These are gradually expanded to include important
functions. Later, the functionality of SQL databases is explained and the
readers learn how they can be integrated into a PHP program. At the end
there is an application example that shows the interaction of PHP and SQL
makes clear.
Since PHP is the programming language most commonly used for server-side
programming of Internet applications
comes, there are innumerable programs that take advantage of this. This is
not just about individual software that has been programmed for a very
special web application and is only used for this. There are also countless
other programs that provide functions that are useful for many websites.
Users can download these and install and run them on their web server. Much
of it is available free of charge because it is free software. Other products,
however, require a fee. PHP is often used for blog software, for example.
Popular blog systems such as Wordpress and Serendipity are programmed in
this language. PHP is also a leader in the area of content management
systems (CMS). Examples are Joomla, TYPO3 and Drupal. There are also
shop systems such as Magento, forum software such as phpBB, customer
relationship management systems such as SugarCRM and many other
programs. This small list not only makes it clear how many applications were
written in PHP. In addition, they show an important field of activity for PHP
programmers. In most cases you are allowed to adapt the source code to your
own needs. A frequent task is therefore to modify small details of these
programs so that they correspond exactly to the wishes of the client. In
addition, it is usually possible to expand the functionality of the software with
small additional programs - so-called plug-ins. This is also an important task
for PHP programmers.
2.1 HTML
an important basis for programs in PHP In the introduction it was shown that PHP is used
for the creation of dynamic Internet pages. Static pages, on the other hand, use HTML. The following
section deals with exactly this markup language. However, this only represents a contradiction at first
glance. Because almost every website that is created with PHP also uses HTML code. The connection
is that the output of a PHP program is normally in HTML. When the server executes the appropriate
program, it generates an ordinary HTML page. It then forwards this to the user's browser, which then
displays it like a static page. The dynamic element here lies in the execution on the server, in which
individually adapted pages are created. All of the following steps are exactly the same as for displaying
a traditional Internet page. It follows that every PHP programmer must have a very good knowledge of
HTML . In order to write a program whose output is to take place in HTML, it is of course necessary to
know exactly the structures and functions of this markup language. In addition, it is common to only
program individual elements of a website in PHP. This means that a normal HTML page is created
first. PHP scripts are only inserted in those places where dynamic content is required in order to insert
the corresponding information. Readers who have no previous knowledge of HTML should therefore
acquire these prior to further reading. In this series, a book has also appeared on this topic, which is
excellently suited for this purpose. This explains the design of Internet pages with HTML from the
ground up. A detailed explanation on this topic is not possible at this point. Nevertheless, the most
important basics should be briefly presented for repetition. A website actually consists of ordinary text
modules. With the help of tags, however, various functions are assigned to them. This makes it
possible, for example, to mark headings or paragraphs or to design certain text areas in bold or italic. In
addition, these tags are suitable for lists and tables. Tags are always in angle brackets: <> . This
contains a combination of letters that makes the function clear - for example, h1 for the main heading,
p for a paragraph or i for italics. An example of an HTML tag would be <h1> . Most HTML tags
need to be opened and closed. The slash is used for the final day. In order to close the above example, it
would be necessary to insert the tag </h1> . The following example illustrates the use of HTML tags:
</p>
The actual page content is in the body tag (<body> ). Before that, a head tag (<head> ) is usually
used. This contains further information on the HTML version used, the page title, a brief description
and other important information. The entire document is in HTML tags (<html> ). The structure of the
HTML document looks like this:
<html>
<head> Here you can find further information about the document.
</head>
The first program is now ready. The way it works is extremely simple. When the server executes this
code, only the title “My first program ” appears on the screen.
Now it is only necessary to save the written code as a file. The file name can be freely chosen. It is only
important to use the ending .php. This is how the server executing the program recognizes that this is a
PHP file. With some text editors it is necessary to remove the standard option - saving as a txt.
Document - when saving. In order to keep an overview at all times, it is advisable to select self-
explanatory names, for example: first_program.php.
Now it is necessary to click on the “Start ” button in the line marked “Apache ” . This results in the
web server running. It is now possible to close or minimize the corresponding window. The process
continues to take place in the background. In the next step it is necessary to move the PHP program to
the root folder of XAMPP. This is the “htdocs ” folder . If further programs are added later, it makes
sense to add subdirectories. This improves the overview considerably. If the program has been placed
in the correct directory, it is necessary to call it up via a web browser. For this it is necessary to enter
the following path in the address bar: http: //localhost/erstes_programm.php. If the reader has saved the
file in a subdirectory, the corresponding folder must be in the
Path to be inserted. The result of the first program then appears in the browser.
It often happens that the programmer has a first draft carried out, then looks at the result in the browser
and then makes some changes. If he now wants to check the new version, he must first save it in the
text editor. This is possible as usual via the menu bar. However, since this process has to be repeated
countless times when programming with PHP, it is important to the reader to use the key combination
Ctrl + S for this. A lot of time can be saved in this way. Then it is necessary to refresh the page in the
browser. This is possible with the circular arrow next to the address bar or by pressing the F5 key.
3.4 Exercise: Writing a simple program in PHP
In the following section, what you have learned is to be put into practice, so there are two exercises
here that you should solve on your own. The necessary knowledge was imparted in the previous
sections. After the two exercises are the solutions
inserted to control your results. However, there are several possible solutions for many tasks. It is
therefore always advisable to call up the control program in the browser in order to check for yourself
whether it meets all requirements. The suggested solutions shown here are for comparison and are also
useful if you are stuck with the programs on your own.
1. Create a program that welcomes visitors to your home page.
Show three different ways to represent the number 8 as output from a PHP program and explain the
differences. Solutions:
1.
This program is almost identical to the example that was described in the text. The only difference is
that it uses different text for rendering. In addition to the two tags for identifying the PHP script, it is
important to pay attention to the quotation marks and the semicolon. <? phpprint "8";?> In this case
the output of the print function uses the number 8 as a string. That's because it's in quotation marks.
No mathematical operations are possible with this. <? php
print 8;?> In the second example, the output is completely identical. However, the program does not
treat the value as a character string, but as a number. Therefore, in a further step here it would be
possible to carry out further calculations. <? phpprint 2 * 4;?> In the last example, the number 8 is not
inserted directly into the print function. It is the result of the term 2 * 4. Since this expression is not in
quotes, PHP treats it as a mathematical operation and automatically calculates the result.
Chapter 4
Combine PHP and HTML
When designing websites with PHP, there is a very close connection between the programming
language and the HTML code. The goal in this application area is always to use PHP to output correct
HTML pages. Therefore, before creating a program with PHP, it is always a good idea to consider what
the output should look like. It is therefore important to design the relevant page in HTML. Then it is
necessary to mark the places that use dynamic content. Then these areas have to be replaced by a PHP
script. These small program pieces should now generate content that is adapted to the respective
context. However, they are intended to perform exactly the same function as the corresponding
elements in the original HTML page. It is therefore necessary for PHP programmers to take this close
connection between PHP and HTML into account. On the one hand, it is important to integrate the PHP
scripts sensibly into the HTML page. On the other hand, it is necessary that every single one of these
scripts outputs valid HTML code. The following sections present the way in which it is possible to
combine PHP and HTML.
Since this is a character string, it is of course necessary to use quotation marks. This is particularly
important here, since the angle brackets also have special functions in PHP. If these are not clearly
identified as part of a character string, this leads to syntax errors so that the server cannot execute the
program. In this example, the server is running the program and returns the output <h1> Welcome to
my homepage </h1> and transmits this code to the browser. This then only shows the desired heading:
Welcome to my homepage. However, it is large and bold, which shows that the browser has recognized
the text as a heading and is displaying it accordingly. This can also be done through the
Check source code display. Therefore it is necessary to click with derrechten click on the appropriate
page and "View source code then dieOption " select. The text then appears with the appropriate tags.
Usually, a website doesn't just consist of a single heading. For this reason, it is usually necessary to
have several elements output with PHP. In principle it is possible to put all different elements in the
same print command. That way, however, the code becomes very cluttered. It is therefore advisable to
use a separate print command for each individual area :
<? phpprint "<h1> Welcome to my homepage! </h1>"; print "<p> 1st paragraph </p>"; print "<p> 2nd
paragraph </p>";?>
When the program is now executed, the heading will first appear on the page
in large characters. Below that, the first and second paragraphs follow with
some space and in much smaller font. The output is therefore exactly as
desired. However, it makes sense to take another look at the source code of
the relevant page. It is noticeable that all the components listed on the page
are on the same line. With a small program like in this example this is
certainly not a big problem. With large pages, however, the source code
becomes extremely confusing. This has extreme disadvantages when
programming in PHP. Often times, when the programmer makes a small
mistake and the page doesn't display correctly, it is very helpful to examine
the source code to see what the problem is. However, if all of the code
appears on a single line, it is almost impossible to find the bug.
If the source text is called up again after this small change, it appears much
better ordered, as each element is on its own line.
Chapter 5
Variables: an important element of PHP programming
With the programs presented so far, some readers may have asked themselves
why it was actually necessary to program the code with PHP. The same effect
would have been possible with pure HTML code. That would be easier and
clearer. This objection is certainly correct. The first program examples were
so simple that no real programming language would be required for them.
But that changes in this chapter. This introduces variables. These are
placeholders that can have different values. Each variable has a unique name
that enables access . As an illustrative example, it is possible to imagine the
variables as drawers in a dresser. Each of them is labeled with its own name.
The variable always remains the same, but the content can change. These
drawers can contain very different things - for example, documents, pens or
coins. It is similar with variables. There are also different types here. Mostly
these are strings or numbers. Various operations can be carried out with the
contents - both in the example with the chest of drawers and with variables.
Users can move pens from one drawer to another that already has some pens
in it. With the documents it is possible to combine them and create a longer
text. The possibilities always depend on the type of content. That also applies
to the variables. With variables, the numbers
completely different operations are possible than if there are strings in them.
The contents of the drawers may change occasionally. At a certain point in
time, however, it is always precisely defined. This also applies to the
variables. A query of the value gives a clear result at any given point in time.
A special case occurs when a variable has not yet been defined. This can be
compared to an empty drawer. However, the return value clearly indicates
that no content is available yet. Variables represent an important basis for the
design of dynamic web pages. Often, only a variable is inserted into the print
function. This can result in very different expenses - depending on its value.
<? php $ integer = 5; $ comma number = 5.555; print $ integer; print "<br>"; print $ comma number;?>
Computer programs often distinguish between many different types of
numbers. These can be whole numbers that are referred to as integers. There
are also point numbers. Each type of number is limited in its size, so that the
memory space required for it is fixed. In many programming languages, it is
necessary to specify exactly what kind of number a variable is. The program
reserves a memory space of the appropriate size. PHP programmers don't
have to worry about that, however. The interpreter takes on this task
independently. To assign a numeric value to a variable, it is only necessary to
declare it accordingly and to fill it with content. This works almost exactly
the same as with text variables:
<? php $ integer = 5; $ comma number = 5.555; print $ integer; print "<br>"; print $ comma number;?>
The command print "<br>"; generates the HTML tag <br> in the source code.
This in turn leads to a line break on the screen. Without this command, both
numbers would be without spaces or
Line breaks are output one after the other.
<? php $ inventory = 5; print "<p> Available articles:"; print $ inventory; print "</p> \ n"; $ inventory
= 4; print "<p> Available articles:"; print $ inventory ; print "</p> \ n";?>
This program indicates the inventory for a specific article and displays it on
the screen. After that, one of these items will be sold, so only four units are
available. The new value is then assigned to the variable and then displayed
again to make the results clear.
This program shows that a variable can easily be assigned a new value. In
practice, however, it is not very smart to use specific values for this. Because
if another item is sold, this function cannot be used again because
the new value would have to be adjusted to 3 for this. Therefore, it makes
more sense to perform a math operation. This can be used with any starting
value and can therefore be used for every sale, regardless of how many items
are currently available: <? Php $ stock = 5; print "<p> Available items:"; print $ stock;
print " </p> \ n "; $ stock = $ stock-1; print" <p> Available articles: "; print $ stock; print" </p> \ n ";?>
The display on the screen is exact the same as the previous program.
However, it is now possible to change the output value of the variable and set
it to 6, for example. In this case the program adjusts the values automatically.
The variable refers to itself and performs an arithmetic operation with its
original value. Many other calculations can be performed in exactly the same
way - for example additions, multiplications, or divisions. The following list
shows some important mathematical operators : + Additions - Subtraction *
Multiplications / Division ** Powers (only from PHP version 5.6) Since
many programs need to increase or decrease the value of a variable by one
unit, this is why a short form is also available. Instead of the line $ stock = $
stock-1; it is quite simply possible $ consisted--; to insert. The command $
consisted ++; however, increases the value of this variable. This saves a lot of
programming time. The point operator is particularly important for editing
text. This is used to connect two text variables with one another. This is very
useful for composing a text from different variables. If, for example, a
personalized address of the visitor is to appear on the page, this can be
combined from the salutation and the name:
<? php $ salutation = "woman"; $ name = "Miller"; $ reader address = $ salutation. "". $ name; print "
<h1> Hello"; print $ reader address; print "! </h1> \ n ";?>
The variable $ reader address arises from a link between the variables $ address
and $ name . It is important that
Please note that there is a space between the two variables in quotation marks
and is also connected with the period operator. Without this addition, the
program would combine the two words with each other and output them
without the space. This example shows another possible application of the
dot operator. Three different print functions are required for the simple
greeting of the reader . This is relatively cumbersome. It is therefore
advisable to combine the various outputs with the dot operator and to
summarize them in a single print command: print "<h1> Hello". $ Reader address. "!
</h1> \ n"; This command is significantly shorter, but the functionality does not
change.
In this case, the index number is assigned consecutively and begins with 0.
This creates exactly the same array as in the previous example. To check the
results, it is useful to refer to the array
on the screen. For the time being, it is necessary to create a separate print
command for each individual field for this purpose :
<? php $ product = array (1, "Drilling machine", 45, "Powerful drilling machine for drilling and
screwing work", 23); print $ product [0]. "<br> \ n"; print $ product [1]. "<br> \ n"; print $ product [2].
"<br> \ n"; print $ product [3]. "<br> \ n"; print $ product [4]. "<br> \ n ";?>
In this example, the individual fields are accessed via an index number. This
has numerous advantages. For example, functions can be created in this way
that access the individual fields using mathematical operations. The problem,
however, is that these values are not self-explanatory. Of course, when
creating the array, the programmer knows that field 0 stands for the item
number, field 1 for the product name and field 2 for the price. However, it
may be that he forgets this after a while. If he then wants to make changes to
the program, he has to
Check carefully which index number stands for which content. To avoid this
problem, it is also possible to use self-explanatory terms for it. This shape is
called an associative array.
<? php $ product = array (); $ product ['item number'] = 1; $ product ['product name'] = "drill"; $
product ['price'] = 45; $ product ['description'] = "Powerful drilling machine for drilling and screwing
work"; $ product ['number'] = 23;?>
To reflect this array, the output must also be adjusted. The full program is
therefore:
<? php $ product = array ('Article number' => 1, 'Product name' => "Drilling machine", 'Price' => 45,
'Description' => "Powerful drilling machine for drilling and screwing work", 'Quantity' => 23); print $
product ['item number']. "<br> \ n"; print $ product ['product name']. "<br> \ n"; print $ product
['price']. "<br> \ n "; print $ product ['description']." <br> \ n "; print $ product ['quantity']." <br> \ n ";?
>
The text that appears on the screen is exactly the same as in the previous
screenshot. In addition, it is possible to create composite arrays. In the
example described here, it would be useful to use the
to display the entire range of goods. However, since this would be very
extensive, this is to be limited in the example to three products, each with
three properties - article number, product name and price. To access the
individual contents, it is now necessary to enter both indices:
<? php $ assortment = array (); $ assortment [0] ['item number'] = 1; $ assortment [0] ['product name']
= "drill"; $ assortment [0] ['price'] = 45 ; $ range [1] ['item number'] = 2; $ range [1] ['product name'] =
"circular saw"; $ range [1] ['price'] = 79; $ range [2] ['item number '] = 3; $ assortment [2] [' product
name '] = "Belt sander"; $ assortment [2] [' price '] = 89; print $ assortment [0] [' product name ']. "<br>
\ n "; print $ assortment [1] ['product name']." <br> \ n "; print $ assortment [2] ['product name']." <br>
\ n "; print $ assortment [0] [ 'Price']. "<br> \ n"; print $ range [1] ['Price']. "<br> \ n"; print $ range [2]
['Price']. "<br> \ n ";?>
The individual variables can easily be combined with the dot operator. This is
also how you insert the HTML tags for paragraphs and line breaks.
3.
<? php $ customer data = array (); $ customer data [0] ['customer number'] = 10001; $ customer data
[0] ['first name'] = "Heinz"; $ customer data [0] ['last name'] = " Mahler "; $ customer data [1]
['customer number'] = 10002; $ customer data [1] ['first name'] =" Eva "; $ customer data [1] ['last
name'] =" Müller "; $ customer data [2 ] ['Customer number'] = 10003; $ customer data [2] ['First
name'] = "Michael"; $ customer data [2] ['Last name'] = "Mayer"; print "Customer number:". $
Customer data [0] ['Customer number']. ", First name:". $ Customer data [0] ['first name']. ", Last
name:". $ Customer data [0] ['last name']. "<br> \ n"; print " Customer number: ". $ Customer data [1]
['customer number'].", First name: ". $ Customer data [1] ['first name'].", Last name: ". $ Customer data
[1] ['last name']." <br> \ n "; print" Customer number: ". $ customer data [2] ['customer number'].", first
name: ". $ customer data [2] ['first name'].", last name: ". $ customer data [ 2] ['Last Name']. "<br> \
n";?>
Chapter 6
Decisions through if queries
Computer programs usually contain many areas that should only be executed
under certain conditions. There are also numerous examples of this that can
be used in a PHP program for an online shop. If the customer has already
placed an item in the shopping cart here, it makes sense to display it.
However, if there is no product here, this is not necessary. In this case, the
program must carry out a query. Only if the result has a certain value does it
carry out the corresponding function. In the example, the program must
therefore first query the number of items in the shopping cart. Only if this is
greater than zero will it display the shopping cart on the screen. If such a
query should be formulated in ordinary language, it could read something
like this: “If the shopping cart contains at least one item, it should be
displayed on the screen. " The key term" Wenn " - in English" if " - is
usually used. Almost all computer programs also use this expression for this.
For this reason, they are referred to as an if query.
There are also a few other comparison operators :! = Executes the function if
the values are not equal. <= Executes the function if the first value is less
than or equal to the second value. > = Executes the function if the first value
is greater than or equal to the second value.
Or
if ($ var1 <5 && $ var2 == 7) {print "Variable 1 is less than 5 and variable 2 is 7.";}
The reader may have noticed that, in contrast to the previous examples, a
complete program - with the opening and closing tags and with the
declaration of the variables - is given. The reason for this is that it makes
sense at this point to insert the program once into the text editor and run it in
the browser. In the next step it is possible to change the values of the
variables so that the conditions are met or not. It is noticeable that the
browser not only displays the corresponding text when exactly one of the two
conditions is met, but also when this applies to both specifications. However,
in some programs this is not desirable. In these cases the exclusive or is used.
This is inserted with the keyword “ xor” . If the program is changed
accordingly, the browser will only display the text if one of the two
conditions is met and the other is not. Another logical operator is the logical
not, which is represented by an exclamation mark. This reverses the truth
value of the
Condition to. This means that the program only executes the function if the
corresponding condition is not met:
if (! ($ var <5)) {print "The variable 1 is not smaller than 5.";
}
These programs assume that there are only two different options for
specifying gender. This means that if the letter m for male has not been
entered as gender , it is automatically a woman. This assumption is usually
correct, but it can sometimes lead to errors. For example, it is possible that a
user did not provide this information, so that the variable remains empty. In
this case it would not be advisable to automatically address the reader as
“woman ” . Therefore it makes sense to further differentiate the query. A
branched query is used for this purpose:
if ($ gender == "m") {print "<h1> Hello Mr.". $ surname. "! </h1> \ n";
}
else {
if ($ gender == "w") {print "<h1> Hello Mrs.". $ surname. "! </h1> \ n";} else {print "<h1> Hello!
</h1> \ n" ;
}
}
This program ensures that the salutation with “woman ” is only used if the
gender is given as female. If there is no entry or a completely different value,
the program decides to address it neutrally with “Hello ” . However, this
type of branching is relatively complicated and is only intended to serve as an
explanation. In practice, it is common to use the “ elseif” command instead .
The following program works in exactly the same way, but is a bit simpler.
if ($ gender == "m") {print "<h1> Hello Mr.". $ surname. "! </h1> \ n";} elseif ($ gender == "w") {
print "<h1> Hello Mrs.". $ surname. "! </h1> \ n";} else {print "<h1> Hello! </h1> \ n";}
This is just a suggested solution. There are many other correct solutions as
well. If you have chosen a different method, you should change the
corresponding values in the array and thus try out whether your program
outputs the correct information for all combinations.
Chapter 7
Extending the functionality of a program through loops
Repeating an identical activity over and over is a great torment for most
people. The monotonous occupation leads to boredom and inhibits
performance. However, it is precisely this task that is the great strength of a
computer program. It often repeats a simple function hundreds or even
thousands of times - in a matter of seconds and without any errors. Now one
could assume that this monotonous activity falls back on the programmer,
since he performs the same functions countless times in your program. But
there is a simple trick to avoid this: the use of loops. It is only necessary to
specify the condition under which the program should execute the loop. It is
then only necessary to enter the corresponding commands once. The program
then executes these until the condition is no longer met - regardless of
whether it takes ten or a million runs. This chapter introduces the use of loops
. These play a very important role in almost all computer programs -
regardless of whether it is a PHP program for designing websites or other
software in a different programming language. Loops are therefore of
enormous importance for all programmers and are indispensable tools.
This program already shows that it is possible to use loops to perform a large
number of functions with just a few commands. It is also possible to refer to
the index variable for each individual run. In this way, for example, the
square numbers can be easily displayed: <? Php $ i = 0; while ($ i <10) {$ i ++; print $ i
* $ i. "<br> \ n";}?> This program multiplies the index variable by in each run
itself and in this way creates the square of that number. Since it makes sense
for this series to begin with the number 1, the index number must be
increased before the command for the output. Alternatively, it would be
possible to prefix the print command, as in the previous program, but to add
the value 1 to the calculation: print ($ i + 1) * ($ i + 1). "<br> \ n"; The functionality
remains the same for both options and generates the following output on the
screen:
It often happens that the loop body is only to be executed under a certain
condition. In these cases it is necessary to integrate if- queries into the loop
body. The following example should serve as an explanation. There is a
composite array that contains the product name, price and number of
available units for three different products. The loop should then list all
products with the associated price - but only if at least one item is in stock. In
this case it is possible to click on the individual fields
of the array with a variable. The index variable is ideal for this.
<? php $ assortment = array (); $ product [0] ['product name'] = "drill"; $ product [0] ['price'] = 45; $
product [0] ['quantity'] = 6 ; $ product [1] ['product name'] = "circular saw"; $ product [1] ['price'] = 79;
$ product [1] ['quantity'] = 0; $ product [2] ['product name '] = "Belt sander"; $ product [2] [' Price '] =
89; $ product [2] [' Quantity '] = 11; $ i = 0; while ($ i <3) {if ($ product [$ i] ['Quantity']> 0) {print "
<p> Product:". $ product [$ i] ['Product name']. "Price:". $ product [$ i] ['Price'] . "Euro </p> \ n";} $ i
++;}?>
Several program lines are required for a while loop. First it is necessary to
introduce the index variable and fill it with a value.
Then the programmer has to specify the condition. Finally, it is necessary to
increase the value of the index variable in the loop body. To reduce the effort,
it makes sense to use a for loop instead. Here , all these commands are
summarized in one line. This alternative is always useful if the loop should
complete a fixed number of runs or if a certain value should be counted in it.
The for loop is introduced by the term for . This is followed by a bracket in
which the value of the variable is introduced first. This is followed by the
condition and finally the specification in which way the index variable is to
be changed in each pass. The individual parts are separated from one another
with a semicolon. The first program in this section serves as an example. This
can be represented as follows without changing the functionality using the for
loop:
In this example, the functionality is exactly the same as the while or for loop.
This also applies to all other programs in which the loop is to be executed
with a fixed number of runs. Which method is used depends solely on the
preferences of the programmer. However, there is one important difference
that can affect the way it works in some programs: With the for and while
loops, the condition is checked at the beginning. The loop body is only
executed if the condition is met. With the do-while loop, however, the
commands in the loop body are always executed at least once. Only then is
the condition checked. If it is fulfilled, another cycle follows. If it is not
fulfilled, the loop is aborted. The following two are intended to distinguish
this
Program examples clarify : <? Php $ number = 50; $ condition = true; while
($ condition) {print "<p> Current number:". $ number. "</p> \ n"; $ number -; $ condition = ($
number> 20);}?>
And
<? php $ number = 50; $ condition = true; do {print "<p> Current number:". $ number. "</p> \ n"; $
number -; $ condition = ($ number> 20 );} while ($ condition);?>
These programs output the number of a specific article. With each run - for
example when selling a unit - the number is reduced. When the inventory
drops to 20, the program halts the loop because the current inventory is too
low. The functionality of the two alternatives is exactly the same. The
difference becomes clear, however, if the value is set to false when
introducing the variable $ condition . In this case, the while loop is not executed
because the condition is not met at the beginning. The do-while loop executes
the loop body anyway. The condition is set to true so that the loop is run
through as often as before until the number has assumed the value 20.
<? php $ product = array (1, "Drilling machine", 45, "Powerful drilling machine for drilling and
screwing work", 23); foreach ($ product as $ content) {print $ content. "<br> \ n";} ?>
This program first determines an array with various details about a product.
The keyword foreach must be at the beginning of the loop . This is followed
by a round bracket and the name of the array. Then there is another key term:
as. After that it is necessary to name a new variable. This serves as a copy of
the contents of the array inside the loop. If the variable just introduced is now
used in the loop, it reproduces one field of the array in each run - until all
entries have been listed. This results in the following output in the browser:
With this knowledge it is now possible to modify the program from section
7.1. Readers who have already understood how the foreach loop works are
welcome to try this conversion themselves. <? php $ assortment = array (); $ product [0]
['product name'] = "drill"; $ product [0] ['price'] = 45; $ product [0] ['quantity'] = 6 ; $ product [1]
['product name'] = "circular saw"; $ product [1] ['price'] = 79; $ product [1] ['quantity'] = 0; $ product
[2] ['product name '] = "Belt sander"; $ product [2] [' price '] = 89; $ product [2] [' number '] = 11;
foreach ($ product as $ content) {if ($ content [' number ' ]> 0) {print "<p> Product:". $ Content
['Product Name']. "Price:". $ Content ['Price']. "Euro </p> \ n";}}?>
For the conversion it is first necessary to remove the introduction and the
increase of the index variables, since these are no longer necessary when
using a foreach loop. Then the foreach loop must be introduced. Inside the
brackets are the name of the array and, after the term as, the variable that is to
display the contents in the loop. After that it is only necessary to adapt the
print command. In this way it is possible to add another product to the array.
This is now automatically taken into account during playback. A foreach loop
also allows a composite array to be output. In contrast to the previous
example, it is not necessary to address the individual fields of the second
level individually. The following program lists the contents of the entire
array: <? Php $ assortment = array (); $ product [0] ['product name'] = "Drill"; $ product [0] ['Price']
= 45; $ product [0] ['Quantity'] = 6; $ product [1] ['Product name'] = "Circular saw"; $ product [1 ]
['Price'] = 79; $ product [1] ['Quantity'] = 0; $ product [2] ['Product name'] = "Belt sander"; $ product
[2] ['Price'] = 89; $ product [2] ['number'] = 15; foreach ($ product as $ level1) {foreach ($ level1 as $
level2) {print $ level2. "<br> \ n";} print "<br>" ;}?> A nested foreach loop is required for
this. The outer loop refers to the first level. The entries of the second level are
like another array for each individual field of the first level
understand. Therefore, another foreach loop is necessary for this . For this, the
individual entries of these small arrays are reproduced in the variable $ level2
according to the same scheme . The additional print command with the HTML
tag <br> ensures an additional line break after all information on a particular
article has been output. This creates groups that belong together when
outputting to the screen:
1.
<? php $ i = 0; while ($ i <10) {$ i ++; print $ i. "<br> \ n";}?> <? phpfor ($ i = 0; $ i <10; $ i ++ )
{print ($ i + 1). "<br> \ n";}?> <? php $ i = 0; do {print ($ i + 1). "<br> \ n";
$ i ++;} while ($ i <10);?> 2. <? php $ assortment = array (); $ assortment [0] ['product'] = "apple"; $
assortment [0] ['price' ] = 1.99; $ range [0] ['special offer'] = false; $ range [1] ['product'] = "pear"; $
range [1] ['price'] = 0.99; $ range [1] ['Special offer'] = true; $ range [2] ['Product'] = "Tomato"; $ range
[2] ['Price'] = 2.49; $ range [2] ['Special offer'] = false; $ assortment [3] ['product'] = "Zucchini"; $
assortment [3] ['price'] = 1.49; $ assortment [3] ['special offer'] = false; foreach ($ assortment as $
content) {if ($ content ['special offer']) {print "Warning special offer! <br> \ n";} print $ content
['product']. "<br> \ n"; print $ content ['price']. " <br> <br> \ n ";}?>
3.
<? php $ assortment = array (); $ product [0] ['product name'] = "drill"; $ product [0] ['price'] = 45; $
product [0] ['quantity'] = 6 ; $ product [1] ['product name'] = "Circular saw"; $ product [1] ['price'] =
79; $ product [1] ['quantity'] = 0; $ product [2] ['product name '] = "Belt sander"; $ product [2] [' Price ']
= 89; $ product [2] [' Quantity '] = 15; foreach ($ product as $ level1) {foreach ($ level1 as $ field name
= > $ level2) {print $ fieldname. ":". $ level2. "<br> \ n";} print "<br>";}?>
Chapter 8
Functions in PHP
A computer program often contains many hundreds of lines of program code,
and it is often difficult to keep track of them. For this reason it makes sense to
give the whole a structure. This is done by functions that allow a certain part
of the program to be outsourced. The main program can easily access these
functions by calling their names. Sometimes it even happens that the actual
main program only consists of a few lines. These call functions that contain
the fundamental components of the program. Each of them in turn uses many
other functions that give the software a clear structure. Functions not only
offer the advantage that they make the program clearer. In addition, they can
save the programmer a lot of work. In many cases it happens that a certain
sequence of instructions occurs very frequently in a program. Programming
them over and over again would take a lot of work. It also increases the risk
of errors. However, if the corresponding commands are swapped out into a
function, it is possible to call them up simply by the function name. This
significantly reduces the work. Functions are therefore of great importance
for complex programs. Like almost all programming languages, PHP offers
the option of creating functions and integrating them into a program.
The use of round brackets after the function name is noticeable in this
function. At first glance, these seem to be completely useless. However, they
represent an important part of the function syntax and must be used in any
case. In this simple example, the brackets are empty and do not affect the
result. For many functions, however, they are filled with content. The content
of the brackets is used to transfer variables to the function. They only remain
empty if no transfer of values from the main program is necessary. In all
other cases there must be a variable name here. This takes on the value that
the main program transfers. It is important to only use this variable within the
function. In this example it would be possible to control the content of the
output through a variable. This would make it possible in a later step, for
example, to adapt the greeting to the time of day and to address the reader
with “Good morning ” , “Good day ” or “Good evening ” depending on the
time . If a variable is to be used, it is also necessary to specify its content in
brackets when the function is called:
<? php
function greeting ($ text) {print $ text;} greeting ("Good morning!");?>
In this example, the value of the variable was inserted directly into the
brackets when the function was called. However, it is common to use a
variable for this. This makes it possible to adapt the content, whereby the
programmer can transmit not just a single variable, but any number. In this
case it is necessary to separate the individual values with a comma - both
when defining the function and when calling it.
<? phpfunction greeting ($ text, $ address) {print $ text. "". $ address. "!";} $ greeting = "Good
morning"; $ reader = "Mr. Miller"; greeting ($ greeting, $ reader );?>
8.2 Return values of the functions
In the previous examples, the functions were used to perform a certain action.
After they were executed, their task was complete and the program made no
further reference to them. However, there are also many applications where
the function should calculate a certain value and return this to the main
program. This can then save it and use it for further tasks. Return values are
used for this purpose. The return value is determined by the return command .
This has to be integrated into the body of the function. It is possible to simply
specify a variable after this key term that contains the return value: function
doubling ($ value) {$ value = $ value * 2; return $ value;} Alternatively, the programmer
can insert the mathematical operation directly after the return command. In
this case it must be in round brackets: function doubling ($ value) {return ($ value * 2);}
Different variable types can be used for the return value. In this way it is
therefore not only possible to transmit numbers to the main program, but also
character strings and truth values.
In order to include the return value in the main program, it is possible to
assign the value of the corresponding function to a variable. This is done just
like assigning ordinary values with an equal sign.
<? phpfunction doubling ($ value) {return ($ value * 2);} $ result = doubling (5); print $ result;?>
Another alternative is to integrate the return value directly into the print
function - or into many other PHP commands:
<? phpfunction duplication ($ value) {return ($ value * 2);} print duplication (5);?>
It is important to note that each function can return a maximum of one value.
However, it can also be an array. If you want the function to return multiple
values, you need to pack them into an array. It is then possible to resolve this
again and reproduce it in individual variables.
It not only describes which tasks the corresponding functions take on. In
addition, it is specified exactly which values the main program must transmit
and which return values the function generates. The online documentation is
a very important tool for using pre-built functions in a program.
1.
<? phpfunction potency ($ value) {$ result = array (); for ($ i = 0; $ i <10; $ i ++) {$ result [$ i] = $
value ** ($ i + 1); } return $ result;} $ powers = potency (2); foreach ($ powers as $ output value)
{print $ output value. "<br>";}?>
2. File functions.php:
<? phpfunction potency ($ value) {$ result = array (); for ($ i = 0; $ i <10; $ i ++) {$ result [$ i] = $
value ** ($ i + 1); } return $ result;} function output ($ powers) {foreach ($ powers as $ output value)
{print $ output value. "<br>";}}?>
File main.php: <? Phpinclude ("functions.php"); output (potency (2));?> 3. For this task
you need the commands rand () and sqrt (), the functionality of which is
described in the online documentation becomes. This results in the following
program: <? Php $ random number = rand (); $ root = sqrt ($ random number); print "The root of".
$ Random number. "Is". $ Root. ". <br> \ n"; ?>
Chapter 9
Object-oriented programming: classes,
objects and methods
The previous chapters described the basic functions of the PHP programming
language. With loops, if queries and functions, a wide range of programs can
be created for very different applications. In the introduction, however, it was
already mentioned that PHP is an object-oriented programming language.
This is a concept that is particularly suitable for large and complex programs.
However, it is not easy to understand the details of object-oriented
programming. This topic represents an important focus of the computer
science course. Experienced programmers take care of the creation of
complex programs with object orientation. In this textbook, however, the
topic will be briefly introduced. On the one hand, it is important that the
reader gets to know the basics of this concept - for example to understand a
program code that another programmer has created. On the other hand, there
are numerous frameworks that simplify the creation of web projects. There
are often prefabricated objects that allow the integration of special functions.
In order to be able to use this tool, it is necessary to know at least the basics
of object-oriented programming. However, this book can only explain the
most important basics. There are numerous textbooks available that are
entirely devoted to object-oriented programming and explain all the details.
Object-oriented programming focuses on the object.
This is an element that has specific properties. It is possible to think of these
objects as different everyday objects. Objects of the same type also have
similar properties - albeit in different ways. In the case of objects of a
different type, however, different properties are also important. For example,
while size, color and ripeness play an important role in the case of an apple,
the speed, fuel consumption and the number of seats are decisive parameters
for a car. Classes are also of great importance for object-oriented
programming. These specify the basic properties that must be taken into
account when describing an object. There are also methods. These are used to
carry out various actions with the objects.
9.1 The class: the basis of object-oriented
programming
As indicated in the previous section, the properties that an object can assume
play an important role in object-oriented programming. There are usually a
very large number of possible properties. However, it is important to identify
the critical areas. As already mentioned, speed, fuel consumption and the
number of seats play an important role for an author. But every car is
characterized by other parameters - for example, length, width, brand and
color. At the beginning it is therefore necessary to consider which features
are important for a particular application. For example, when a programmer
creates a platform on which used cars are offered for sale, he has to consider
what information is required for this. If he then creates an object for a certain
car, he has to assign all important properties to it.
This is where the classes come into play. This is a pattern to which all objects
are oriented. In this example, the template specifies exactly which properties
are to be described for a car. The variables that contain the corresponding
values are called members. If an object that symbolizes a car is to be created,
it must follow these guidelines carefully. This means that there must be a
value for all properties that are defined in the class. Since the class is the
template for an object, the first step in object-oriented programming is to
define a class. The keyword class Use. This is followed by the name of the
class, which the programmer can freely choose. The properties that all objects
of this class have in curly brackets.
<? phpclass car {private $ seats; public $ speed; public $ fuel consumption;}?>
<? phpinclude ("class_auto.php"); $ myCar = new Car (); $ myCar-> speed = 150; $ myCar-> fuel
consumption = 7; print "Speed:". $ myCar-> speed. "km / h <br> \ n "; print" Fuel consumption: ". $
meinAuto-> fuel consumption." l / 100km <br> \ n ";?>
The next car is a sporty two-seater. Therefore an attempt should be made to
change the number of seats. For that comes
analogous to the previous example, the command $ meinAuto-> Sitzplaetze = 2; for
use. However, the following error message appears:
The reason for this is that this member has been declared private. This means
that access from the main program is not possible. For this, methods are used
that are explained in the following section.
In order to access one of its members within a class, it is necessary to use the
keyword $ this followed by the symbol “ ->” and the name of the member
(without the dollar sign). The function must be public so that the main
program can access it. When the method is called, the program transfers the
value that is to be inserted. This is recorded in the variable $ number . When a
method changes a member, it is common to combine the function name from
the component set and the name of the member (with an uppercase letter). If,
on the other hand, it asks for a value, it is common to combine the name from
the term get and the name of the property. If the corresponding method is
integrated in the class, it can be called from the main program. It is necessary
to put the object name and the symbol "->" in front of the name of the
function:
$ meinAuto-> setSitzplaetze (2);
<? phpclass Auto {private $ seats = 5; public $ speed; public $ fuel consumption; public function
setSeats ($ number) {$ this-> seats = $ number;
}}?>
<? phpinclude ("class_auto.php"); $ myCar = new Car (); $ myCar-> speed = 150; $ myCar-> fuel
consumption = 7; print "Speed:". $ myCar-> speed. "km / h <br> \ n "; print " Fuel consumption: ". $
meinAuto-> fuel consumption." l / 100km <br> \ n "; $ meinAuto-> setSitzplaetze (2);?>
Main program
<? phpinclude ("class_product.php"); $ drill = new product (); $ drill-> setArticle number (1); $ drill->
setProductname ("drill"); $ drill-> setprice (45); $ drill -> set description ("Powerful drilling machine
for drilling and screwing work"); $ drilling machine-> setNumber (23);?>
When you run this program, only an empty field appears in the browser, since
no function has been inserted for the output. For the check, it is only
important to ensure that no error messages appear. In order to display the
content of the individual members, you can add methods to the program that
take on this task.
<? phpclass Auto {private $ seats = 5; public $ speed; public $ fuel consumption; public function
setSeats ($ number) {$ this-> seats = $ number;} public function getSeatpaces () {return $ this-> seats;
}}
?>
Main program:
<? phpinclude ("class_auto.php"); $ myCar = new Car (); $ myCar-> speed = 150; $ myCar-> fuel
consumption = 7; print "Speed:". $ myCar-> speed. "km / h <br> \ n "; print" Fuel consumption: ". $
myAuto-> fuel consumption." l / 100km <br> \ n "; $ meinAuto-> setSitzplaetze (2); print" Seats: ". $
meinAuto-> getSitzplaetze (). "<br> \ n"; ">?>
Chapter 10
Now it's time to read in the data. The fgets command is used for this purpose.
It is necessary to enter the name of the handle in round brackets and
optionally, separated by a comma and the desired length in square brackets.
This command reads in the data until a line break, the end of the file or - if
specified - the maximum length is reached. (Alternatively, the commands
fread and fscan are available, but these cannot be discussed in detail at this
point; however, the interested reader can find detailed information on this in
the PHP online documentation.) The way in which the fgets command works
shows that this reads each line individually. This means that a while loop is
necessary for this , which repeats this process until the end of the document is
reached. As in this example it is already known to contain 10 lines
it would be possible to simply specify ten runs. However, it is simpler and more
practical to use the feof function . This returns a Boolean variable. Its value is
false as long as the end of the file has not yet been reached. As soon as this is
the case, the value changes to true, resulting in the following program:
<? php $ handle = fopen ("example.txt", "r"); $ result = array (); if ($ handle) {$ i = 0; while (! feof ($
handle)) {$ content = fgets ($ handle); $ result [$ i] = $ content; $ i ++; print $ content. "<br> \ n";}
fclose ($ handle);} else {print "The file could not be opened. <br> \ n ";}?>
This program not only reads the corresponding numbers from the file. It also
saves the individual values in the $ result array and outputs the numbers on the
screen. It is also important to explain the fclose command . This closes access
to the file and should always be inserted after the last use of the handle. In
order to check the functionality of the program, it is possible to change the
output values in the text file a little. If you run it again, the changed values
should be displayed on the screen.
<form method = "post" action = "datenabfrage.php"> Name: <input type = "text" name = "name">
<br> E-Mail: <input type = "text" name = "e-mail "> <br> <input type =" submit "value =" Submit ">
</form>
<form method = "post" action = "datenabfrage.php"> Name: <input type = "text" name = "name">
<br> E-Mail: <input type = "text" name = "e-mail "> <br> <input type =" submit "value =" Send ">
</form> <? php $ handle = fopen (" example3.txt "," w "); if ($ handle)
{if (! empty ($ _ REQUEST ['name']) &&! empty ($ _ REQUEST ['e-mail'])) {if ($ _REQUEST
['name']! = "") {$ name = $ _REQUEST ['name']; fputs ($ handle, $ name. "\ n");} if ($ _REQUEST
['e-mail']! = "") {$ email = $ _REQUEST ['e-mail'] ; fputs ($ handle, $ email . "\ n");}} fclose ($
handle);} else {print "The file could not be opened. <br> \ n";}?>
This program writes the values that the user enters via the input fields into a
new file with the name example3.txt. This is created in the same folder in
which the program is located. The if- query with the condition (! Empty ($ _
REQUEST ['name']) &&! Empty ($ _ REQUEST ['e-mail'])) needs to be explained. . This
ensures that the following part is only carried out if the user has already
entered a value in the form field. If this has not yet been done, the contents of
$ _REQUEST ['name'] and $ _REQUEST ['e-mail'] have not yet been defined. That
would lead to error messages. The query with the condition ($ _REQUEST
['name']! = "") Is also available. This checks whether a value has been entered via
the form field. If this is not the case, the program does not write any data to
the file.
Solution:
<? phpif (! empty ($ _ REQUEST ['number'])) {print "<p> Your input has been recorded and used to
calculate the new document. </p> \ n";}?> <form method = " post "action =" task11-1.php "> Enter any
number: <input type =" text "name =" number "> <br>
<input type = "submit" value = "Send"> </form> <? phpif (! empty ($ _ REQUEST ['number'])) {$
handle = fopen ("numbers.txt", "r"); $ handle2 = fopen ("result.txt", "w"); $ result = array (); if ($
handle) {$ i = 0; while (! feof ($ handle)) {$ content = fgets ($ handle); $ result [$ i] = $ content; $ i
++;} if ($ _REQUEST ['number']! = "") {$ factor = $ _REQUEST ['number']; foreach ($ result as $
value ) {$ value = intval ($ value) * $ factor; fputs ($ handle2, $ value. "\ n");}} fclose ($ handle);
fclose ($ handle2);} else {print "The file could cannot be opened. <br> \ n ";}}?>
Note: The first if query (before the input form) checks whether there is a value for $ _REQUEST
['number'] - that is, whether an entry has already been made. Therefore, the corresponding notice
does not appear the first time the page is accessed. The program only outputs it when the user
enters a value and the page loads again.
Chapter 11
Databases: The efficient alternative for data storage
Databases are used to retrieve the data for the execution of a PHP program or
to store new values in it. However, this is not the only way to do this. In the
previous chapter, files were used for precisely this purpose. For this reason it
is interesting to compare both alternatives before starting to use the databases.
From this comparison it quickly becomes clear why in practice databases are
used almost exclusively. One of the biggest problems with files is that they
are not multi-user capable. In the case of a website, however, many visitors
often access the data at the same time. Therefore files are not suitable for this
task. When using databases, on the other hand, it is not a problem if many
users use the data at the same time. Files are also very insecure. If a user
receives access rights, he can view and change all content. The structures are
also openly visible and it is not a problem to manipulate values manually. In
the case of databases, however, the structures are not externally recognizable.
That makes it difficult to influence. In addition, there is a very differentiated
access protection. Another advantage is the simpler structuring of the data.
This is particularly important for extensive projects with large amounts of
data
It is easier to keep track of things when using databases, and it is also much
easier to access a specific value. When using files, finding a specific entry is
a big problem. However, a database solves this task quickly and efficiently.
For these reasons, it is advisable to always use databases for Internet
applications. Files are actually only used when data is to be exchanged with
the user. However, they are not recommended for internal data storage.
Another advantage of MySQL is that it works great with PHP. Among other
things, the PHP Database Object (PDO) is used for this purpose. This is an
object that contains many functions that are necessary for interacting with the
database. This makes it particularly easy for the programmer to integrate the
relevant queries. Although access is usually via the PHP program, there are
also situations in which direct access to MySQL is necessary. This allows the
data to be entered manually, for example change or determine the structures.
It also makes it a little easier to learn how to use the databases. Therefore
there is a user interface called phpMyAdmin, which enables direct access. To
achieve this it is necessary to have the
Enter the URL http: // localhost / phpmyadmin / in the address line of the
browser.
11.4 SQL: the database language for working with
MySQL
In the previous chapters it was already stated that a PHP program
communicates with the DBMS in order to query, insert or change data. In
order for this communication to run smoothly, it must use uniform
commands. This is where the SQL database language comes into play. When
a PHP program sends a command to the DBMS, it must use this language.
SQL contains all of the functions required to work with databases, but it is
not a programming language. For example, SQL does not provide functions
for loops or branches, which are important parts of a full-fledged
programming language. SQL's history goes back well into the past century -
to the 1970s. It was then that IBM developed the first relational database,
which was named System R. For this novel
Database model also required a new language. That is why the company
developed SQL - at that time, however, under the name SEQUEL. In 1986
the US standards institute ANSI published a corresponding standard for the
first time. In the following year, the international standardization organization
(ISO) followed suit. That was the basis for SQL becoming the most widely
used database language.
Chapter 12
Basic operations for dealing with MySQL databases
Now that the theoretical basics of the databases have been explained, it is
time to put it all into practice. This chapter introduces the basic SQL
commands and enables the reader to create databases, create tables and
manipulate data. To make this task as simple as it is clear, the SQL
commands should be entered via the user interface phpMyAdmin, which also
contains Buttons that enable the corresponding actions to be performed
without the use of SQL commands. However, since the goal of this exercise
is to learn how to use SQL, the actual commands are used. These are also
important later to enable communication with a PHP program. However, this
represents a further step and is only described in Chapter XIV.
The corresponding commands can now be inserted in the window that then
appears. First it is necessary to create a database. This forms the basis for all
other applications. The CREATE command is used for this purpose, which has
already been mentioned in the previous section. This is followed by the key
term DATABASE, which indicates that MySQL should create a new database. A
name is required to clearly define this. This can be chosen freely. Since the
following examples simulate applications for an online shop, the database is
to be named onlineshopDB . The appendix DB makes it clear that this is a
database. Although this form of naming is not absolutely necessary, it makes
it easier to identify the individual elements later. Just like in PHP, it is also
necessary in SQL to end the individual commands with a semicolon. The
complete command to create the database is therefore: CREATE DATABASE
onlineshopDB;
After entering it, it is necessary to click the OK button at the bottom right of
the screen. The page then reloads. At first glance, no changes can be seen.
Nevertheless, a new database was created as a result. This can be checked by
clicking on the “Databases ” field on the far left in the menu bar. The entry
onlineshopDB now appears next to the existing databases .
Many data types can be assigned additional attributes. For example, the
addition unsigned to numbers is important. This means that the corresponding
field can only contain positive numbers. But the maximum size doubles.
Further attributes will be used in the further course of this book, but they will
only be explained at the appropriate point. To create a table, it is necessary to
choose a name for it. The first table should contain the products of the online
shop. Hence it bears the name os_produkte . The prefix os_ indicates that the
table belongs to the onlineshopDB database and thus improves clarity. While
this is not absolutely necessary, it is highly recommended.
The individual columns now follow. The first column should contain a
consecutive index. That makes it easier to access the individual lines. The
name of this column should be called p_id . The prefix p_ makes it clear that
this column belongs to the table os_product. Whole numbers of the type
integer are used as the data type . Not null , unsigned , auto_increment and primary
key are used as attributes . Not null means that this value cannot be null. In
computer science, however, this does not refer to the number 0, which can
certainly occur. The expression zero means that there is no value. Since an
index does not normally take on negative values, the unsigned attribute is used.
The addition auto_increment causes the DBMS to automatically assign
consecutive numbers for these cells. The primary key attribute means that the
data record can be uniquely identified by the values in this column. This is
important, for example, for references from other tables. Next, the column
p_article number follows as an integer with the attributes not null , unsigned and unique
. The first two additions are already known. The last entry means that no
identical values may occur in this column. This is important because each
item number can only be assigned once. A variable of the type varchar (40 )
with the attribute not null is used for p_productname . 40 characters should be
sufficient even for very long product names. The variable type decimal (7,2) is
used for p_preis . The first number in brackets indicates the total number of
possible digits. The second number tells how many of them are decimal
places. Not null and unsigned are used as attributes . The p_beschreibung column
uses the type varchar (300) . Since the description is significantly longer than
the product name, more space is required. Attributes are not necessary here.
Finally, there is the p_number column - an integer variable with the unsigned
attribute. Now it is possible to create the table. Here comes the
CREATE command used - but with the addition TABLE . This is followed by
the name of the table and finally, within brackets, the individual columns
with their variable types and attributes. The individual attributes are only
separated from one another by a space. A comma follows the entry for a
column:
CREATE TABLE os_product (p_id integer unsigned not null auto_increment primary key, p_article
number integer unsigned not null unique, p_productname varchar (40) not null, p_price decimal (7,2)
unsigned not null, p_description varchar (300), p_number integer unsigned);
1.
CREATE TABLE os_kunden (k_id integer unsigned not null auto_increment primary key,
k_kundennummer integer unsigned not null unique, k_name varchar (40), k_first name varchar (40),
k_strasse varchar (60), k_hausnummer smallint unsigned, k_telefonnummer integer unsigned);
Integer variables are used for the numerical values . If no negative values
occur, it is possible to define them as unsigned . The smallint type was only
chosen for the house number , as this usually does not have very high values.
Entries of the type varcha r with a suitable length are used for all texts , but
this is only a suggested solution. It is also possible to use other types.
2.
INSERT INTO os_kunden (k_kundennummer, k_name, k_forname, k_strasse, k_hausnummer,
k_telefonnummer) VALUES (2001, 'Schulz', 'Michael', 'Bahnhofstraße', 23, 0123456789);
After the same pattern, it is possible to add many more customers with
different personal data.
3.
UPDATE os_kunden SET k_hausnummer = 22 WHERE k_id = 1;
Chapter 13
Other important SQL functions
The previous chapter described the essential basics of the SQL database
language. Functions for creating databases and for inserting, changing or
deleting entries were presented. These commands are essential for
manipulating data, but there are many other functions in SQL that go far
beyond these capabilities. The following chapter introduces some commands
that allow many other applications when using SQL databases. The following
explanations use the table os_kunden , which was created in the previous
exercise, as an example . If this does not yet exist, it makes sense to create it
using the solutions given and to fill it with some content. In this way the
reader can try out the commands described for himself.
The asterisk indicates that all entries are to be displayed in the corresponding
table. After the keyword FROM the name derTabelle follows. However, it is
not always desirable to get all of the existing values. Often only a small
fraction of them are required. The SELECT command therefore offers the
option of selecting very specific subsets. For this purpose, it is possible to
replace the asterisk with the name of a column. The command SELECT k_name
FROM os_customers; displays all entries in the Name column, for example. It is
not only possible to provide an indication. The programmer can also specify
multiple columns. These must be separated by a comma: SELECT k_customer
number, k_name, k_first name FROM os_customers; With the commands presented so
far, it is possible to call up the values in one or more columns. However, it is
often necessary to use the contents of a particular cell. For this purpose it is
necessary to also specify the appropriate line. As a rule, the index variable is
used again for this. Before this, the keyword WHERE must be :
SELECT k_name FROM os_customers WHERE k_id = 2;
This command returns the name of the customer. This is stored in the second
row of the table. It is also possible to use logical operators for these queries.
Often, for example, the logical or is used. This is represented in SQL by the
term OR . This makes it very easy to query entries from several lines. For
example, the following command returns the values of the third and fourth
lines:
SELECT k_name FROM os_ customers WHERE k_id = 3 OR k_id = 4;
It is also possible to use the logical and. An example using the following
table should illustrate when this is useful:
This command changes the house number in the column with the index
number 3, since this is the result of the term 1 + 2. Mathematical operations
are also very often used to increase or decrease the value of a certain cell. In
an online shop, for example, it often happens that a customer orders another
item. In this case it is necessary to increase the value of the column
k_ordered_article by one unit. For this purpose it is possible to use the
following command:
UPDATE os_kunden SET k_ordered_artikel = k_bestelte_artikel + 1WHERE k_id = 3;
This command shows that SQL uses the names of fields in a similar way to
variables in a programming language. To change the content, it is possible to
use an arithmetic expression in which the field name refers to its previous
value.
Chapter 14
Integrate SQL database in PHP
In the previous chapters, the SQL commands for creating and manipulating
the databases were entered directly via phpMyAdmin. However, this method
is rarely used in practice. The user interface also has options for performing
the corresponding actions without SQL. This is much easier and usually
faster. The method used so far was only used to learn about and practice
using various SQL commands. Although there are practical alternatives to
using SQL queries when accessing the database directly, it is very important
to learn and internalize the corresponding terms. This is due to the fact that in
many applications the database is not accessed via phpMyAdmin, but via a
PHP program. This makes it possible to automate the corresponding
processes so that the software independently queries the data from the
database or enters it in it. SQL is used for the communication between the
PHP program and the database. For this reason, the commands presented in
the previous chapters are indispensable tools for PHP programmers. The
following sections show how a database can be connected to a PHP program.
They also explain how the SQL commands are integrated into the software in
order to enable smooth communication with the database.
After the command for the connection has been created, it is a good idea to
verify that this operation was successful. The following if query is used for
this. Should an error occur, the function mysqli_connect_errno () returns the value
true . In this case it is important to generate an error message. If the
corresponding user was created correctly via phpMyAdmin and if all data
were entered correctly, the message “Connection successfully established. ”
Appear. For practice purposes, it makes sense to change the username or
password to an invalid value. If the program is now executed, a
corresponding error message appears. After the program has ended, it is
important to close the connection again with the command mysqli_close () .
This method is rarely used in practice. The main reason for this is that the
individual commands often require a great deal of program code that is often
repeated. However, there are methods that have a slightly higher level of
abstraction and therefore make many tasks much easier. An example of this is
PDO. This abbreviation stands for PHP Database Object. To generate a
handle for a database with PDO, only the following command line is
necessary:
$ dbh = new PDO ("mysql: dbname = onlineshopDB; host = localhost", "user1", "abc");
Since this is an object, it must be created with the keyword “ new” . The
required class PDO is
already stored in the PHP library so that the user does not have to worry
about it. The key term mysql appears in brackets: dbname = followed by the name of
the database. The term host = localhost follows, separated by a semicolon . This
is followed by the user name and password - each separated by a comma. The
complete program for connecting to the database looks like this:
<? phptry {$ dbh = new PDO ("mysql: dbname = onlineshopDB; host = localhost", "user1", "abc");
print "Connection successfully established."; $ dbh = null;} catch (PDOException $ e ) {print $ e->
getMessage ();}?>
When using PDO, too, it makes sense to check whether the connection was
successful. However, this does not happen with an if query, but with
exception handling. The keyword try is used for this. If the commands in the
following curly braces do not cause problems, the interpreter will carry them
out as normal. However, if this is not the case - because a connection to the
database was not possible - it creates an exception. This must then be caught
by the term catch . The commands used for this cannot be explained further at
this point. All that needs to be said is that they cause an appropriate error
message to appear if the connection was not possible. In addition, the
command $ dbh = null; to explain. As already explained in one of the previous
chapters, the term zero in computer science means
that there is no value at all. Assigning the value null to the handle destroys it.
The PDO then automatically terminates the connection.
Now it is necessary to send this command to the database. This is done with
the mysqli_query () command . In the brackets you will find the name of the
handle and then the corresponding SQL command in quotation marks. Since
this is very long in this example, it makes sense to use the dot operator to
distribute it over several program lines.
<? php $ dbh = mysqli_connect ("localhost", "user1", "abc", "onlineshopDB"); if
(mysqli_connect_errno ()) {print "No connection to the database possible:" .mysqli_connect_error ();}
else
{print "Connection successfully established."; mysqli_query ($ dbh, "CREATE TABLE
os_bestellungen". "(b_id integer unsigned not null auto_increment primary key,". "b_article number
integer unsigned not null,". "b_customer number integer unsigned not null," . "b_preis decimal (7,2)
unsigned not null,". "b_ number integer unsigned);");} mysqli_close ($ dbh);?>
With PDO it is also relatively easy to check whether an error has occurred
during the transmission of the data. This is done using the errorInfo () function ,
which is also a method of PDO and returns an array. The first field contains
an SQL error code. If no problems occurred, this has the value 0. Therefore,
the content of the if query is only executed if there is an error. The second
field is output, which contains another error code. Finally, the third field is
displayed, which contains a description. The corresponding check should be
integrated in the following program. To fill the table with content, it is only
necessary to change the value of the variable $ sql. All other components of
the program remain the same:
<? php $ sql = "INSERT INTO os_bestellungen". "(b_article number, b_customer number, b_price, b_
number)". "VALUES (1011, 2001, 45.99, 1);"; try {$ dbh = new PDO ("mysql: dbname =
onlineshopDB; host = localhost "," user1 "," abc "); print" Connection successfully established. "; $
dbh-> query ($ sql); $ error = $ dbh-> errorInfo (); if ($ error [0]> 0) {
print "Error code:". $ error [1]. "<br>". $ error [2];} $ dbh = null;} catch (PDOException $ e) {print $
e-> getMessage ();}?>
<? php $ sql = "SELECT b_preis FROM os_bestellungen;"; try {$ dbh = new PDO ("mysql: dbname =
onlineshopDB; host = localhost", "user1", "abc"); print "Connection successfully established. < br> \ n
"; $ result = array (); $ i = 0; foreach ($ dbh-> query ($ sql) as $ content) {print" content of the cell: ". $
content ['b_price']. "<br> \ n"; $ result [$ i] = $ content ['b_preis']; $ i ++;} $ error = $ dbh-> errorInfo
(); if ($ error [0]> 0) {print "Error code:". $ Error [1]. "<br>". $ Error [2];} $ dbh = null;} catch
(PDOException $ e) {print $ e-> getMessage ();}?>
2.
Fill out the table with two complaints.
3.
Design a program that queries the date of the complaint in line 1 and displays
it on the screen. To do this, use the fetchAll () method.
1.
<? php $ sql = "CREATE TABLE os_reklamationen". "(r_id integer unsigned not null auto_increment
primary key,". "r_customer number integer unsigned not null,". "r_article number integer unsigned not
null,". "r_date date);"; try {$ dbh = new PDO ("mysql: dbname = onlineshopDB; host = localhost",
"user1", "abc"); $ dbh-> query ($ sql); $ dbh = null;} catch (PDOException $ e ) {print $ e->
getMessage ();}?> 2. <? php $ sql = "INSERT INTO os_reklamationen". "(r_customer number,
r_article number, r_date)". "VALUES (1015, 2005, '2018-03- 25 '); "; $ sql2 =" INSERT INTO
os_reklamationen "." (R_customer number, r_article number, r_date) "." VALUES (1013, 2012,' 2018-
03-29 '); "; try {$ dbh = new PDO ("mysql: dbname = onlineshopDB; host = localhost", "user1",
"abc"); $ dbh-> query ($ sql);
$ dbh-> query ($ sql2); $ error = $ dbh-> errorInfo (); if ($ error [0]> 0) {print "Error code:". $ error
[1]. "<br>". $ error [2];} $ dbh = null;} catch (PDOException $ e) {print $ e-> getMessage ();}?> 3.
<? php $ sql = "SELECT r_date FROM os_reklamationen WHERE r_id = 1; "; try {$ dbh = new PDO
(" mysql: dbname = onlineshopDB; host = localhost "," user1 "," abc "); $ return = $ dbh-> query ($
sql); $ result = $ return- > fetchAll (PDO :: FETCH_ASSOC); print "Date of the complaint:". $ result
[0] ['r_date']. "<br> \ n"; $ error = $ dbh-> errorInfo (); if ($ error [0]> 0) {print "Error code:". $ error
[1]. "<br>". $ error [2];} $ dbh = null;} catch (PDOException $ e) {print $ e- > getMessage ();}?>
Chapter 15
Application example: recording customer data via the
Internet
After the basics of PHP and SQL were presented in the previous chapters, the
last chapter is devoted to a small practical example. Since the examples in
this book were always geared towards the functions for creating an online
shop, this topic will also be taken up in the last section. However, it would be
too time-consuming to design a complete shop software with all functions.
For this reason, only a small section should be recorded here. The resulting
pages are intended to enable a new customer to register. For this purpose, a
form field is created through which he can enter his personal information.
The program then processes these and transfers them to a database. Once
entered, the customer is redirected to a page that displays all the information
so that they can review them. If he confirms the information, the data will
remain in the database and the customer will be redirected to a new page that
will notify him of the successful completion. However, if it indicates that the
data is incorrect, the entry is deleted and the data input page reappears. This
example focuses primarily on PHP and SQL. To make the task easier, the
HTML code is kept as simple as possible. An appealing design is completely
dispensed with. Readers with good HTML and CSS knowledge are welcome
to design this themselves as a supplement. Since this program will consist of
several files, it makes sense to create a new folder for it.
The four areas meta title, meta description, main heading and page content
should now be replaced by a corresponding variable and output in a print
function. In the first three cases, this function should be within the
corresponding HTML tags so that the variable only reproduces pure text. The
HTML tags should only be included in the corresponding variable for the
page content, since they represent part of the individual content. This results
in the following code:
<html><head> <title> <? php print $ meta_title;?> </title> <meta name = "description" content = <?
php print $ meta_description;? >>
</head><body> <h1> <? php print $ main heading;?> </h1> <? php print $ page content;?> </body>
</html>
After the basic structure of the page has been determined, it is necessary to
create a table in which the texts are stored. This should be named os_inhalt
and, in addition to the index, have four columns with the corresponding
contents. It is important to note that the page content can be very extensive. It
is therefore necessary to plan enough space for this. To create the table, the
following SQL command should be entered inphpMyAdmin:
CREATE TABLE os_inhalt (i_id integer unsigned not null auto_increment primary key, i_title varchar
(60), i_description varchar (200), i_headline varchar (100), i_content varchar (2000));
<? php $ sql = "SELECT i_title, i_description, i_headline, i_content FROMos_inhalt WHERE i_id =
1;"; try {$ dbh = new PDO ("mysql: dbname = onlineshopDB; host = localhost", "user1", "abc" ); $
rueckgabe = $ dbh-> query ($ sql); $ result = $ rueckgabe-> fetchAll (PDO :: FETCH_ASSOC); $
meta_title = $ result [0] ['i_title']; $ meta_description = $ result [ 0] ['i_description']; $ main heading =
$ result [0] ['i_headline'];
$ page content = $ result [0] ['i_content']; $ dbh = null;} catch (PDOException $ e) {print $ e->
getMessage ();}?>
This part only needs to be placed in front of the previously created area with
the HTML structure. The page for displaying the form is now ready. Only
one small detail is still missing: adding the content to the database. This
should again be done directly via phpMyAdmin. For the fields i_title ,
and i_headline it is only necessary to think of a small text. For the last
i_description
field, however, a complete form must be created. This should be inserted in a
table with two columns for better clarity. On the left is what content should
be entered. The corresponding form field follows on the right. The HTML
code for the page content therefore looks like this:
<p> Register as a new customer! </p> <form method = "post" action = "ausgabe.php"> <table> <tr>
<td> Name: </td> <td> <input name = "name" type = "text"> </td> </tr> <tr> <td> First name: </td>
<td> <input name = "first name" type = "text"> </td> </tr><tr><td>Straße:</td> <td> <input name =
"strasse" type = "text"> </td> </tr> <tr> <td> ZIP code: </td>
<td> <input name = "plz" type = "text"> </td> </tr> <tr> <td> Place: </td> <td> <input name = "place"
type = "text "> </td> </tr> <tr> <td> E-Mail: </td> <td> <input name =" mail "type =" text "> </td>
</tr> <tr > <td> Telephone number: </td> <td> <input name = "tel" type = "text"> </td> </tr> <tr>
<td> Password: </td> <td> < input name = "password" type = "password"> </td> </tr> <tr> <td
colspan = "2" align = "center"> <input type = "submit" value = "login"> < / td> </tr> </table> </form>
The page content should now be saved as text in the i_content cell . Although
the entry is very extensive, this is possible without any problems, since this
cell was previously allocated a correspondingly large space. For an appealing
display of the source code it is only necessary to replace all line breaks with
the symbol \ n . This results in a very extensive INSERT command:
INSERT INTO os_inhalt (i_title, i_description, i_headline, i_content) VALUES ('Login page for our
online shop', 'On this page you can register as a new customer for our online shop', 'Welcome to our
online shop', '<p> Register as a new customer! </p> \ n <form method = "post" action =
"ausgabe.php"> \ n <table> \ n <tr> \ n <td> Name: < / td> \ n <td> <input name = "name" type =
"text"> </td> \ n </tr> \ n <tr> \ n <td> First name: </td> \ n
<td> <input name = "first name" type = "text"> </td> \ n </tr> \ n <tr> \ n <td> Street: </td> \ n <td> <
input name = "street" type = "text"> </td> \ n </tr> \ n <tr> \ n <td> ZIP code: </td> \ n <td> <input
name = "plz" type = "text"> </td> \ n </tr> \ n <tr> \ n <td> Location: </td> \ n <td> <input name =
"location" type = "text"> </td> \ n </tr> \ n <tr> \ n <td> E-Mail: </td> \ n <td> <input name = "mail"
type = "text"> </td> \ n </tr> \ n <tr> \ n <td> Telephone number: </td> \ n <td> <input name = "tel"
type = "text"> </td> \ n </tr> \ n <tr> \ n <td> Password: </td> \ n <td> <input name = "password" type
= "password"> </td> \ n </tr> \ n <tr> \ n <td colspan = "2" align = "center"> <input type = "submit"
value = "Register"> </td> \ n </tr> \ n </table> \ n </form> \ n ');
As soon as this command has been entered via phpMyAdmin, the display of
the form field is possible:
Finally, this page is supposed to transfer the values that are now stored in the
object to the database. This is done with a single INSERT command. This
should be saved again in the $ sql variable. To find the correct values, it calls
the get methods on each individual member.
$ sql = "INSERT INTO os_kunden". "(k_name, k_first name, k_strasse, k_plz, k_ort, k_mail, k_tel,
k_passwort, k_ customer number)". "VALUES ('". $ new customer-> getName (). "', '" . $ new
customer-> getFirst name (). "','". $ new customer-> getStrasse (). "',". $ new customer-> getPlz (). ",'".
$ new customer-> getOrt (). " ',' ". $ new customer-> getMail ()." ', ". $ new customer-> getTel ().",' ". $
new customer-> getPassword ()." ', ". $ new customer → get customer number () . ");";
Note: In the print version, the sequence of single and double quotes required
for this command is difficult to recognize. In order to avoid confusion, it
should be mentioned that the single quotation marks must always be placed
within the double quotation marks. After this, it is necessary to execute the
command with the query method . The previous program saves all values in
the database and now looks like this:
<? phpinclude ("class_kunde.php"); $ new customer = new customer (); if (! empty ($ _ REQUEST
['name']))) {if ($ _REQUEST ['name']! = "") {$ new customer-> setName ($ _ REQUEST ['name']);}}
if (! empty ($ _ REQUEST ['first name'])) {if ($ _REQUEST ['first name']! = "") {$ new customer->
setFirst name ($ _ REQUEST ['first name']);}} if (! empty ($ _ REQUEST ['street'])) {if ($
_REQUEST ['street']! = "") {$ new customer-> setStrasse ($ _ REQUEST ['street']);}} if (! empty ($
_REQUEST ['plz'])) {if ($ _REQUEST ['plz']! = "") {$ New customer-> setPlz ($ _ REQUEST
['plz']);}} if (! Empty ($ _ REQUEST [' location '])) {if ($ _REQUEST [' location ']! = "") {$ new
customer-> setOrt ($ _ REQUEST [' location ']);}} if (! empty ($ _ REQUEST [' mail ']) )) {if ($
_REQUEST ['mail']! = "") {$ new customer-> setMail ($ _ REQUEST ['mail']);}} if (! empty ($ _
REQUEST ['tel'])) { if ($ _REQUEST ['tel']! = "") {$ new customer-> setTel ($ _ REQUEST ['tel']);}}
if (! empty ($ _ REQUEST ['password'])) {if ($ _REQUEST ['password']! = "")
{$ new customer-> setPasswort ($ _ REQUEST ['password']);}} try {$ dbh = new PDO ("mysql:
dbname = onlineshopDB; host = localhost", "user1", "abc"); $ new customer- > setKundennummer ($
dbh); $ sql = "INSERT INTO os_kunden". "(k_name, k_first name, k_strasse, k_plz, k_ort, k_mail,
k_tel, k_passwort, k_ customer number)". "VALUES ('". $ new customer-> getName ( ). "','". $ new
customer-> getFirst name (). "','". $ new customer-> getStrasse (). "',". $ new customer-> getPlz (). ",'".
$ new customer -> getOrt (). "','". $ new customer-> getMail (). "',". $ new customer-> getTel (). ",'". $
new customer-> getPassword (). "'," . $ new customer-> get customer number (). ");"; print $ sql. "
<br>"; $ dbh-> query ($ sql); $ dbh = null;} catch (PDOException $ e) {print $ e -> getMessage ();}?>
$ sql = "SELECT * FROM os_customers WHERE k_customer number =". $ new customer-> get
customer number (). ";"; $ return = $ dbh-> query ($ sql); $ result = $ return-> fetchAll (PDO ::
FETCH_ASSOC); foreach ($ result as $ content) {print "<p> For the new customer with the customer
number". $ Content ['k_kundennummer']. "The following values were recorded: <br>"; print "Name:" .
$ content ['k_name']. "<br> \ n"; print "First name:". $ content ['k_first name']. "<br> \ n"; print
"Street:". $ content [ 'k_strasse']. "<br> \ n"; print "ZIP:". $ content ['k_plz']. "<br> \ n"; print "City:". $
content ['k_ort']. " <br> \ n "; print" E-Mail: ". $ content ['k_mail']." <br> \ n "; print" Telephone
number: ". $ content ['k_tel']." <br> \ n "; print" Password: ". $ content ['k_passwort']." </p> \ n ";}
The customer should then be able to confirm or reject the data by inserting
two small forms. The first form is very simple. It should only contain the
“Confirm ” button and redirect the visitor to a page that shows that the data
has been properly recorded. The code for this looks like this:
<form method = "post" action = "confirmation.php"> <input type = "submit" value = "confirm">
</form>
The following code is required for the form that is used to correct the values:
<form method = "post" action = "formular.php"> <input type = "hidden" name = "reference" value = "$
new customer-> get customer number ()">
<input type = "submit" value = "Correct"> </form>
If the customer wants to correct the data, he will be redirected to the original
form at the address formular.php. The hidden form field needs to be explained
. This is hidden and is therefore not displayed. It only serves to transmit a
value to the next page. Therefore the customer number is inserted with a PHP
variable. It should be noted that the code, as it stands here, is still invalid, as
HTML and PHP are mixed up. This will be differentiated accordingly later
when this part is entered in a print function. The transfer of the customer
number is necessary because the page to which the users are redirected is to
delete the incorrect data. To do this, it needs to know which data set it is. The
customer number is therefore transmitted as a reference. To display the two
form fields, these must be inserted in a print command. It is important to
insert the character \ in front of the quotation marks, which are part of the
HTML code . This is the only way to ensure correct execution. Now the
frame for the page should be inserted. The pattern from Section 15.1 is used
for this. It is only necessary to change the index number when querying the
database. In addition, the main part should not be inserted via a database,
since it is generated directly by the program. For this it is necessary to fill the
database os_inhalt with a new line via phpMyAdmin. The reader can think of
small texts for the title, description and main heading. The i_content column
remains empty. The program for the output.php page looks like this:
<? php $ sql = "SELECT i_title, i_description, i_headline, i_content FROMos_inhalt WHERE i_id =
2;";
try {$ dbh = new PDO ("mysql: dbname = onlineshopDB; host = localhost", "user1", "abc"); $ return =
$ dbh-> query ($ sql); $ result = $ return-> fetchAll (PDO :: FETCH_ASSOC); $ meta_title = $ result
[0] ['i_title']; $ meta_description = $ result [0] ['i_description']; $ main heading = $ result [0]
['i_headline']; $ page content = $ result [0] ['i_content']; $ dbh = null;} catch (PDOException $ e) {print
$ e-> getMessage ();}?> <html> <head> <title> <? php print $ meta_title;?> </title> <meta name =
"description" content = <? php print $ meta_description;? >> </head> <body> <h1> <? php print $
main heading;?> </ h1> <? phpinclude ("class_kunde.php"); $ new customer = new customer (); if (!
empty ($ _ REQUEST ['name'])) {if ($ _REQUEST ['name']! = "") {$ new customer-> setName ($ _
REQUEST ['name']);}} if (! empty ($ _ REQUEST ['first name'])) {if ($ _REQUEST ['first name']! =
"") {$ new customer -> setVorname ($ _ REQUEST ['firstname']);}} if (! empty ($ _ REQUEST
['street'])) {if ($ _REQUEST ['street']! = "") {
$ new customer-> set street ($ _ REQUEST ['street']);}} if (! empty ($ _ REQUEST ['zip code'])) {if ($
_REQUEST ['zip code']! = "") {$ new customer- > setPlz ($ _ REQUEST ['plz']);}} if (! empty ($ _
REQUEST ['location'])) {if ($ _REQUEST ['location']! = "") {$ new customer-> setOrt ( $ _REQUEST
['location']);}} if (! Empty ($ _ REQUEST ['mail'])) {
The if loop with the isset function determines whether a value has been
passed to the program. This ensures that this part is not carried out the first
time the page is called up, but only when the user wants to correct the values.
The DELETE command should be known as far as possible. The customer
number that was transferred by the hidden form field on the previous page is
used as a reference. The program thus fulfills its tasks and the customer can
access his data
Chapter 16
PHP and Cookies: Recognizing Visitors and Saving
Information
PHP is primarily used to generate dynamic Internet pages. This means that
the content that is displayed on the pages is not always the same. On the other
hand, they are only generated when the visitor calls up the page. This not
only makes it possible to change texts and images quickly and easily. In
addition, this technology allows it to be individually adapted to the visitor. If
you operate a blog or a news portal, it would be possible, for example, to first
present the reader with articles that he has not yet read. The texts that he
already knows are usually not of great importance, so that they can be in the
background. Another alternative is to include a personal address on the page.
This often increases the reader's interest. The individual design is particularly
important when developing a web shop. Among other things, it is necessary
that the customer can call up which articles he has ordered. In order to tailor
the displayed content to the visitor, it is necessary to identify him first.
However, HTTP is a connection-free technology. Therefore, every time the
user calls up a new page, all data is lost. It is of course possible to store the
information permanently in a database. However, in order to personalize the
pages, it is necessary to know who is currently visiting the page. This is the
only way to call up the associated database contents.
If the user comes from one of their own pages, it is relatively easy to forward
the relevant information. We already have a possibility for this in Chapter
15.4. uses: hidden forms. In this example the customer number has been
passed on to the next page. It would be possible to expand this information
further - for example to make the name, the contents of the shopping cart and
other details available. However, it is simpler and safer to store these values
in the database. Then the next page only needs the customer number as a
reference to be able to access it. However, this method has the problem that it
can only be used for the duration of a visit. If the user calls up another page
or closes the browser, all information is lost. It makes sense to use cookies so
that they are still available on your next visit. This chapter shows how these
can be inserted into a PHP page.
16.1 What is a cookie?
The term cookie translates as biscuit or cookie. In computer science,
however, it stands for a small data packet that is sent back and forth between
different computers in order to exchange information. This is not an
executable program, but only data in text form. There are several different
types of cookies in computer science. Most often this term refers to HTTP
cookies. These are used for data exchange between the web browser and the
server. This chapter deals only with HTTP cookies. Other forms are not
important for programming with PHP. When using PHP, the cookie is
generated by the server and transmitted to the user's web browser. For this it
is necessary to insert a corresponding command into the PHP program. It is
then saved on the user's computer. The prerequisite for this is that they accept
the use of cookies. Another alternative
consists in the fact that the cookie is generated directly in the browser.
However, this is not possible with PHP. Client-side scripting languages such
as Javascript are necessary for this purpose. Therefore, this alternative is not
dealt with further here. If a cookie is stored on the computer, the web browser
automatically transmits it to the server when it calls up a page from the server
again. This means that the programmer does not have to request the cookie
first. He receives it - if it is available - always delivered immediately. The
domain whose page it was set is always stored in the cookie. The information
is then available for all pages of the domain. It is therefore not necessary to
use a new cookie for each subpage. However, it is not possible to access
cookies from other domains. Using cookies is extremely practical, but
caution is also required. On the one hand, it is important to observe the legal
provisions. For the use of cookies it is almost always necessary to obtain the
consent of the user. Those who do not run the risk of having to pay
substantial fines. Anyone who wants to use cookies on a website should
therefore find out exactly what the legal regulations for them look like. On
the other hand, there are numerous users who generally block cookies.
Therefore, it makes sense to use them only as additional information. A
website should, however, function properly even without the use of cookies.
PHP is primarily used to generate dynamic Internet pages. This means that
the content that is displayed on the pages is not always the same. On the other
hand, they are only generated when the visitor calls up the page. This not
only makes it possible to change texts and images quickly and easily. In
addition, this technology allows it to be individually adapted to the visitor. If
you operate a blog or a news portal, it would be possible, for example, to first
present the reader with articles that he has not yet read. The texts that he
already knows are usually not of great importance, so that they can be in the
background. Another alternative is to include a personal address on the page.
This often increases the reader's interest. The individual design is particularly
important when developing a web shop. Among other things, it is necessary
that the customer can call up which articles he has ordered. In order to tailor
the displayed content to the visitor, it is necessary to identify him first.
However, HTTP is a connection-free technology. Therefore, every time the
user calls up a new page, all data is lost. It is of course possible to store the
information permanently in a database. However, in order to personalize the
pages, it is necessary to know who is currently visiting the page. This is the
only way to call up the associated database contents.
If the user comes from one of their own pages, it is relatively easy to forward
the relevant information. We already have a possibility for this in Chapter
15.4. uses: hidden forms. In this example the customer number has been
passed on to the next page. It would be possible to expand this information
further - for example to make the name, the contents of the shopping cart and
other details available. However, it is simpler and safer to store these values
in the database. Then the next page only needs the customer number as a
reference to be able to access it. However, this method has the problem that it
can only be used for the duration of a visit. If the user calls up another page
or closes the browser, all information is lost. It makes sense to use cookies so
that they are still available on your next visit. This chapter shows how these
can be inserted into a PHP page.
If you do this now, a blank page will appear. Still something happened. You
can tell when you call up the browser's cookie data. How this works is shown
here using the Google Chrome browser as an example. The procedure is
similar for other browsers. To do this, first click on the three points at the top
right
Click the edge of the picture and then select the Settings menu item.
Then a new page will open. Here you have to scroll down to the very bottom
and click on “Advanced”. On the following page you then have to click on
“Content Settings”
The entry “Cookies” is located at the top. This must be clicked. You then
have to select the menu item “Show all cookies and website data”. A long list
of all the cookies stored on the computer will appear. In it you have to search
for the entry localhost - or use the search function. The cookie with the
designation customer number that we have just set will already appear. If you
click on this, the corresponding entries become visible:
A lot of different information is now available here. Under the term content,
for example, the text that we entered using the setcookie command can be
viewed - i.e. the customer number 12345. In addition, it can be seen at what
time the cookie was created and until when it is valid. The setcookie command
must always be at The beginning of the document is preceded by any HTML
tags, PHP print commands or other output. Even spaces are not allowed to
precede it . The reason for this is that the cookie is transmitted in the HTTP
header. It must therefore be in front of all content on the page. However,
XAMPP does not apply this rule. This means that you can also output content
here before the setcookie command. However, this is strictly not
recommended. If you create such a program and later load it onto a real web
server, it is very likely that it will not work. However, it is possible to use the
setcookie command in an if query. This is not an output, so it does not affect
the structure of the document. For example, it is common to use an if query
to check whether a cookie already exists and to only set a new cookie if it
does not yet exist.
Then it makes sense to insert an else block that outputs an alternative page for
visitors without a cookie. The query of the data will now be clarified using a
short example program. This contains an array with the data from three
different customers. In practice it would of course be necessary to store the
customer data in a database and first load it into the program. In order to keep
the code simple and clear, this step is omitted in this example. The program
then calls
first takes the customer number from the cookie and goes through the array
with a foreach loop to check for a match. If this is found, the program records
the associated salutation and name and outputs a personalized greeting (the
program assumes that if a cookie is present, the associated customer data is
also stored. If this is not the case, this would be the case In order to make the
program more robust, it would make sense in practice to insert an alternative
procedure for this as well.) If there is no cookie, the program asks the visitor
to log in. For this purpose, it offers a link to the program from the previous
example (which in this example is called cookie
If you run the program now (and if the cookie from the previous section is
still saved), you should have a personalized salutation
appear:
If the customer does not exist, the cookie should be invalidated. This is done
with the setcookie command. However, a few seconds should be deducted
from the time () command. This ensures that the expiration date is in the past
and the cookie is therefore invalid. Then an error message appears and a
button that reloads the page. If the customer is present, however, the program
should welcome them and display their saved data. The last part looks like
this:
else {try {$ sql = "SELECT * FROM customers WHERE k_id =". $ _ COOKIE ['customer number'].
";"; $ dbh = new PDO ("mysql: dbname = customerDB; host = localhost", "user1" , "abc"); $ rueckgabe
= $ dbh-> query ($ sql); if ($ rueckgabe-> rowCount ()> 0) {$ result = $ rueckgabe-> fetchAll (PDO ::
FETCH_ASSOC); print "Cordially Welcome! <br> "; print" Your data: <br> "; print" Customer
number: ". $ _ COOKIE ['Customer number']." <br> "; print" Name: ". $ result [0] [' k_name ']. "<br>";
print "First name:". $ result [0] [' k_first name ']. "<br>"; print "City:". $ result [0] [' k_home ']. "
<br>";} else {setcookie ("customer number", 0, time () - 10); print "Cookie data invalid!"; print '<form
method = "post" action = "application example.php"> '; print' <input type = "submit" value = "Next"> ';
print' </form> ';} $ dbh = null;} catch (PDOException $ e) {print $ e-> getMessage (); }}
This completes the page. It now always outputs a suitable display - depending
on whether a cookie is present or whether the user has filled out the form
fields. The complete code looks like this:
<? phpif (empty ($ _ COOKIE ['customer number'])) {if (! empty ($ _ REQUEST ['customer
number'])) {try {$ sql = "SELECT * FROM customers WHERE k_id =". $ _ REQUEST [' customer
number ']. ";"; $ dbh = new PDO ("mysql: dbname = customerDB; host = localhost", "user1", "abc"); $
return = $ dbh-> query ($ sql); if ( $ rueckgabe-> rowCount ()> 0) {setcookie ("customer number", $
_REQUEST ['customer number'], time () + 2592000); print "Successfully logged in."; print '<form
method = "post" action = "application example.php"> '; print' <input type = "submit" value = "Next"> ';
print' </form> ';
} else {print "Invalid customer number. Please enter it again!"; print '<form method = "post" action =
"application example.php">'; print '<input type = "submit" value = "Next">'; print '</form>';} $ result =
$ return-> fetchAll (PDO :: FETCH_ASSOC); $ dbh = null;} catch (PDOException $ e) {print $ e->
getMessage ();}} elseif (! empty ($ _ REQUEST ['name']) and! empty ($ _ REQUEST ['first name'])
and! empty ($ _ REQUEST ['residence'])) {$ sql = "INSERT INTO customers (k_name, k_first name,
k_residence) ". "VALUES (: name,: first name,: place of residence);"; $ sql2 = "SELECT * FROM
customers;"; try {$ dbh = new PDO ("mysql: dbname = customerDB; host = localhost", "user1",
"abc"); $ input = $ dbh-> prepare ($ sql); $ input-> bindParam (': name', $ _ REQUEST ['name'], PDO
:: PARAM_STR, 40); $ input-> bindParam (': first name', $ _ REQUEST ['first name'], PDO ::
PARAM_STR, 40); $ input-> bindParam (': residence', $ _REQUEST ['residence'], PDO ::
PARAM_STR, 40); $ input-> execute (); $ return = $ dbh-> query ($ sql2); $ result = $ return->
fetchAll (PDO :: FETCH_ASSOC); foreach ($ result as $ content) {$ new customer number = $
content [ 'k_id'];}
setcookie ("customer number", $ new customer number, time () + 2592000); print "Your data has been
saved. <br>"; print "Your customer number:". $ new customer number; print '<form method = "post"
action = " application example.php "> '; print' <input type =" submit "value =" Next "> '; print' </form>
'; $ dbh = null;} catch (PDOException $ e) {print $ e-> getMessage ();}} else {print '<table> <tr> <td>
Already registered: </td>'; print '<td> Register again: </td> </tr> <tr> <td> '; print' <form method =
"post" action = "application example.php"> '; print' Customer number: <input type = "text" name =
"customer number"> <br> <br> '; print' <input type = "submit" value = "Send"> '; print' </form> ';
print' </td> <td> '; print' <form method = "post" action = "application example.php"> ' ; print 'Name:
<input type = "text" name = "name"> <br>'; print 'First name: <input type = "text" name = "first
name"> <br>'; print 'City: < input type = "text" name = "residence"> <br> <br> '; print' <input type =
"submit" value = "Send"> '; print' </form> '; print' </ td > </tr> </table> ';}} else {try {$ sql =
"SELECT * FROM customers WHERE k_id =" .
$ _COOKIE ['customer number']. ";"; $ Dbh = new PDO ("mysql: dbname = customerDB; host =
localhost", "user1", "abc"); $ return = $ dbh-> query ($ sql ); if ($ rueckgabe-> rowCount ()> 0) {$
result = $ rueckgabe-> fetchAll (PDO :: FETCH_ASSOC); print "Welcome! <br>"; print "Your data:
<br>"; print "Customer number:". $ _ COOKIE ['Customer number']. "<br>"; print "Name:". $ result
[0] ['k_name']. "<br>"; print "First name:". $ result [0] ['k_first name']. "<br>"; print "City:". $ result
[0] ['k_wohnort']. "<br>";} else {setcookie ("customer number", 0, time () - 10); print "cookie data
invalid!"; print '<form method = "post" action = "application example.php">'; print '<input type =
"submit" value = "next"> '; print' </form> ';} $ dbh = null;} catch (PDOException $ e) {print $ e->
getMessage ();}}?>
1.
<? phpprint '<form method = "post" action = "task1.2.php">'; print 'Name: <input type = "text" name =
"name"> <br> <br>'; print ' <input type = "submit" value = "Next"> '; print' </form> ';?>
2.
<? php $ nutzer = [["Sebastian", 24], ["Marianne", 64], ["Karsten", 14]]; if (! empty ($ _ REQUEST
['name']))) {setcookie (" Visitor ", $ _REQUEST ['name'], time () + 2592000);} $ nameVorhanden =
false; foreach ($ user as $ content) {if ($ content [0] == $ _REQUEST ['name']) {$ age = $ content [1];
$ nameVorhanden = true;}} if ($ nameVorhanden) {
session_start (); $ _ SESSION ['Name'] = $ _REQUEST ['name']; $ _ SESSION ['Age'] = $ age; print
'Your data: <br>'; print 'Name:'. $ _ REQUEST [ 'name']. "<br>"; print 'Age:'. $ age. "<br>"; print
'<form method = "post" action = "task1.3.php">'; print '< input type = "submit" value = "confirm"> ';
print' </form> ';} else {print' Name not saved. '; print' <form method = "post" action = "task1.1.php ">
'; print' <input type =" submit "value =" Next "> '; print' </form> ';}?>
3.
<? phpsession_start (); if ($ _SESSION ['Age'] <18) {print 'Access under 18 not possible.';} else {print
'Welcome!';}?>
This is followed by the design of the email. This should first contain a
personal salutation and then point out to the customer that the invoice is
attached. Since this expression is a little longer, it should first be stored in the
variable content before adding it to the PHPMailer object: $ content = "Dear Sir /
Madam". $ _ REQUEST ['name']; $ content. = ", \ r \ nYour invoice is attached."; Then the mail
is sent via the PHPMailer object. The procedure is almost the same as in
section 2.2. It is only necessary to ensure that the recipient is to be
determined on the basis of the input made previously by the user. The content
is not entered directly, but via the variable content:
$ mail = new PHPMailer (); $ mail-> setFrom ('[email protected]', 'tool online shop'); $ mail->
addAddress ($ _ REQUEST ['address'], $ _REQUEST [' name ']);
$ mail-> Subject = 'Your Invoice'; $ mail-> Body = $ content; $ mail-> addAttachment ($ file); $ mail-
> send ();
The creation of the PDF document and the sending of the e-mail are now
completed. However, the page that opens remains empty so far. Therefore a
short message should be displayed here:
print "Thank you for your order! <br>"; print "Your invoice will be sent to you by email.";
Now you have to close the curly braces of the if query. This is followed by a
short else block that is executed if the customer has not ordered an item. This
only outputs a corresponding message:
The program is now fully completed. The complete code for this looks like
this:
<? php
require_once ('TCPDF-master / tcpdf.php'); use PHPMailer \ PHPMailer \ PHPMailer; use PHPMailer \
PHPMailer \ Exception; require 'C: \ xampp \ composer \ vendor \ autoload.php'; $ html = "<h1>
Invoice </h1> "; $ html. =" <p> Invoice no .: 12345 </p> <br> <br> <br> "; $ price = 0; if ($
_REQUEST ['drill'] ! = 0) {$ html. = $ _REQUEST ['drilling machine']. "Drilling machine (s):"; $
html. = ($ _REQUEST ['drilling machine'] * 34.99). "EUR <br> <br>" ; $ price + = $ _REQUEST
['drilling machine'] * 34.99;} if ($ _REQUEST ['angle grinder']! = 0) {$ html. = $ _REQUEST ['angle
grinder']. "Angle grinder:"; $ html. = ($ _REQUEST ['angle grinder'] * 22.99). "EUR <br> <br>"; $
price + = $ _REQUEST ['angle grinder'] * 22.99;} if ($ _REQUEST ['belt grinder']! = 0 ) {$ html. = $
_REQUEST ['belt sander']. "Belt sander:"; $ html. = ($ _REQUEST ['belt sander'] * 41.99). "EUR <br>
<br>"; $ price + = $ _REQUEST ['belt sander'] * 41.99;} $ html. = "<br> <br> <br> Invoice amount:".
$ Price. "EUR"; if ($ price> 0) {$ file = "Invoice.pdf "; $ pdf = new TCPDF (); $ pdf-> AddPage (); $
pdf-> writeHTML ($ html); $ pdf-> Outp ut (dirname (__ FILE __). '/'. $ file, 'F'); $ content = "Dear Sir
/ Madam". $ _ REQUEST ['name']; $ content. = ", \ r \ nYour invoice is attached. "; $ mail = new
PHPMailer (); $ mail-> setFrom ('[email protected] ',' Tool-Onlineshop '); $ mail-> addAddress
($ _ REQUEST [' address'], $ _REQUEST ['name']); $ mail-> Subject = 'Your invoice'; $ mail-> Body
= $ content; $ mail-> addAttachment ($ file); $ mail-> send () ; print "Thank you for your order! <br>";
print "Your invoice will be sent to you by email.";
} else {print "You have not ordered a product.";}?> Screenshot 73 The confirmation after
the order
2. Use the same HTML form from the previous exercise. However, remove
the field for entering the email address and redirect the visitor to another
page, which should output the content in a PDF document directly via the
browser. Now use the original HTML form again by entering the email
address. Just change the forwarding and design a new page. This should turn
the content into a PDF document
create and save on the server. It then sends this as an attachment to the
specified address.
1.HTML form:
<h1> Please enter the content </h1> <form method = "post" action = "task1.php"> Content: <br>
<textarea name = "content" rows = "10" cols = "30" > Your message </textarea> <br> E-Mail: <input
type = "text" size = "15" name = "mail"> <br> <br> <input type = "submit" value = "send" > </form>
PHP-Script: <? Php $ receiver = $ _REQUEST ['mail']; $ subject = "Automatic E-Mail"; $ from =
"From: PHP-Lehrbuch"; $ text = $ _REQUEST ['content']; mail ($ recipient, $ subject, $ text, $ from);?
>
. <? phprequire_once ('TCPDF-master / tcpdf.php'); $ pdf = new TCPDF (); $ pdf-> AddPage (); $
pdf-> writeHTML ($ _ REQUEST ['content']); $ pdf-> Output ('Task2.pdf', 'I');?>