Вы находитесь на странице: 1из 114

Introduction to Server-Side

Programming
• Before you continue you should have a basic
understanding of the following:
• HTML
• CSS
• JavaScript
• What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor“
• The PHP Hypertext Preprocessor (PHP) is a programming
language that allows web developers to create dynamic
content that interacts with databases.

Prepared by Madam Amina


Cont.
• PHP is a server side scripting language that is
embedded in HTML. It is used to manage
dynamic content, databases, session tracking,
even build entire e-commerce sites.
• It is integrated with a number of popular
databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL
Server.

Prepared by Madam Amina


Common uses of PHP
• PHP can handle forms, i.e. gather data from
files, save data to a file, through email you can
send data, return data to the user.
• You add, delete, modify elements within your
database through PHP.
• Using PHP, you can restrict users to access
some pages of your website.
• It can encrypt data.

Prepared by Madam Amina


What is a PHP File?

• PHP files can contain text, HTML, CSS,


JavaScript, and PHP code.
• PHP code are executed on the server, and the
result is returned to the browser as plain
HTML
• PHP files have extension ".php"

Prepared by Madam Amina


Cont.
• In order to develop and run PHP Web pages three vital
components need to be installed on your computer
system.
• Web Server − PHP will work with virtually all Web
Server software, including Microsoft's Internet
Information Server (IIS) but then most often used is
freely available Apache Server
• Database − PHP will work with virtually all database
software, including Oracle and Sybase but most
commonly used is freely available MySQL database.
• PHP Parser − In order to process PHP script instructions
a parser must be installed to generate HTML output
that can be sent to the Web Browser.

Prepared by Madam Amina


Basic PHP Syntax

• A PHP script can be placed anywhere in the document.


• A PHP script starts with <?php and ends with ?>
• <?php
// PHP code goes here
?>
• A PHP file normally contains HTML tags, and some PHP
scripting code.
• Below, we have an example of a simple PHP file, with a
PHP script that uses a built-in PHP function "echo" to
output the text "Hello World!" on a web page:

Prepared by Madam Amina


Cont..
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
• Note: PHP statements end with a semicolon (;).

Prepared by Madam Amina


Comments in PHP
• A comment in PHP code is a line that is not
read/executed as part of the program. Its only purpose
is to be read by someone who is looking at the code.
• Comments can be used to:
• Let others understand what you are doing.
• Remind yourself of what you did - Most programmers
have experienced coming back to their own work a
year or two later and having to re-figure out what they
did. Comments can remind you of what you were
thinking when you wrote the code
• PHP supports several ways of commenting:
Prepared by Madam Amina
Examples
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
Prepared by Madam Amina
PHP Case Sensitivity

• In PHP, all keywords (e.g. if, else, while, echo,


etc.), classes, functions, and user-defined
functions are NOT case-sensitive.
• In the example below, all three echo
statements below are legal (and equal):

Prepared by Madam Amina


Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Prepared by Madam Amina
Cont..
• However; all variable names are case-sensitive.
• In the example below, only the first statement will
display the value of the $color variable (this is because
$color, $COLOR, and $coLOR are treated as three
different variables):
• <!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
Prepared by Madam Amina
PHP Variables
• Variables are "containers" for storing information.
• Creating (Declaring) PHP Variables
• A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume).
• Rules for PHP variables:
• A variable starts with the $ sign, followed by the name of the
variable
• A variable name must start with a letter or the underscore
character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two
different variables) Prepared by Madam Amina
Cont..
• Note: When you assign a text value to a
variable, put quotes around the value.
• Note: Unlike other programming languages,
PHP has no command for declaring a variable. It
is created the moment you first assign a value
to it.

Prepared by Madam Amina


Example
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
</body>
</html>

Prepared by Madam Amina


Example
• <!DOCTYPE html>
<html>
<body>

<?php
$txt = “www.tpsc.ac.tz";
echo "I love $txt!";
?>

</body>
</html>

Prepared by Madam Amina


Example
• <!DOCTYPE html>
<html>
<body>

<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>

</body>
</html>

Prepared by Madam Amina


Example
• <!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
</body>
</html>

Prepared by Madam Amina


PHP is a Loosely Typed Language

• In the example above, notice that we did not


have to tell PHP which data type the variable
is.
• PHP automatically converts the variable to the
correct data type, depending on its value.
• In other languages such as C, C++, and Java,
the programmer must declare the name and
type of the variable before using it.

Prepared by Madam Amina


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

Prepared by Madam Amina


PHP - Decision Making

• PHP supports following three decision making


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

Prepared by Madam Amina


if...else statement
• Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Prepared by Madam Amina


Examples
• <?php
$t = 30;

if ($t < 20) {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

Prepared by Madam Amina


The ElseIf Statement

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

Prepared by Madam Amina


Examples
• <?php
$t =3;

if ($t < 10) {


echo "Have a good morning!";
} elseif ($t < 20) {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

Prepared by Madam Amina


PHP Global Variables - Superglobals
• Super Global variables are an assosciative array, they
are predefined by PHP. They are superglobal because
they are available in all scopes on script, which means
that they are always accessible, regardless of scope -
and you can access them from any function, class or
file without having to do anything special.
There are several types of Super Global Variables :-
• $_GET
• $_POST
• $_REQUEST
• $_SESSION

Prepared by Madam Amina


PHP $_GET
• PHP $_GET can also be used to collect form
data after submitting an HTML form with
method="get".
• $_GET can also collect data sent in the URL.
• The example below displays a simple HTML
form with two input fields and a submit
button:

Prepared by Madam Amina


Cont.
• Example
• <html>
<body>

<form action="welcome_get.php"
method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type=“email" name="email"><br>
<input type="submit">
</form>

</body>
</html>
Prepared by Madam Amina
Cont.
• When the user fills out the form above and
clicks the submit button, the form data is sent
for processing to a PHP file named
"welcome.php". The form data is sent with
the HTTP GET method.
• To display the submitted data you could
simply echo all the variables. The
"welcome.php" looks like this:

Prepared by Madam Amina


Cont.
<html>
<body>
Welcome
<?php
echo $_GET["name"];
?><br>
Your email address is:
<?php echo $_GET["email"];
?>
</body>
</html>
• The output could be something like this:
• Welcome John
Your email address is john.doe@example.com

Prepared by Madam Amina


PHP $_POST

• PHP $_POST is widely used to collect form data after


submitting an HTML form with method="post".
$_POST is also widely used to pass variables.
• The example below shows a form with an input field
and a submit button. When a user submits the data by
clicking on "Submit", the form data is sent to the file
specified in the action attribute of the <form> tag. In
this example, we point to the file itself for processing
form data. If you wish to use another PHP file to
process form data, replace that with the filename of
your choice. Then, we can use the super global variable
$_POST to collect the value of the input field:

Prepared by Madam Amina


Cont.
• PHP - A Simple HTML Form
• The example below displays a simple HTML form with two input fields
and a submit button:
• Example
• <html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type=“email" name="email"><br>
<input type="submit">
</form>
</body>
</html>
• NOTE
• form action – where to send the form data
• method – how to send the data ( POST)
• Name attributes become the keys used to access the corresponding
fields in the $_POST arrays

Prepared by Madam Amina



Cont.
When the user fills out the form above and clicks the submit button, the form data
is sent for processing to a PHP file named "welcome.php". The form data is sent
with the HTTP POST method.
• To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:
• <html>
<body>
Welcome
<?php
echo $_POST["name"];
?><br>
Your email address is:
<?php
echo $_POST["email"];
?>
</body>
</html>
• The output could be something like this:
• Welcome John
Your email address is john.doe@example.com

Prepared by Madam Amina


Cont.
• The code above is quite simple. However, the
most important thing is missing. You need to
validate form data to protect your script from
malicious code.
• This page does not contain any form
validation, it just shows how you can send and
retrieve form data.

Prepared by Madam Amina


GET vs. POST
• Both GET and POST create an array (e.g. array( key =>
value, key2 => value2, key3 => value3, ...)). This array
holds key/value pairs, where keys are the names of the
form controls and values are the input data from the
user.
• Both GET and POST are treated as $_GET and $_POST.
These are superglobals, which means that they are
always accessible, regardless of scope - and you can
access them from any function, class or file without
having to do anything special.
• $_GET is an array of variables passed to the current
script via the URL parameters.
• $_POST is an array of variables passed to the current
script via the HTTP POST method.

Prepared by Madam Amina


When to use GET?
• The GET method sends the encoded user information appended to
the page request. The page and the encoded information are
separated by the ?character.
• http://www.test.com/index.htm?name1=value1&name2=value2
The GET method produces a long string that appears in your server
logs, in the browser's Location: box.
• The GET method is restricted to send upto 1024 characters only.
• Never use GET method if you have password or other sensitive
information to be sent to the server.
• GET can't be used to send binary data, like images or word
documents, to the server.
• The data sent by GET method can be accessed using
QUERY_STRING environment variable.
• The PHP provides $_GET associative array to access all the sent
information using GET method.

Prepared by Madam Amina


When to use POST?
• The POST method transfers information via HTTP headers.
The information is encoded as described in case of GET
method and put into a header called QUERY_STRING.
• The POST method does not have any restriction on data
size to be sent.
• The POST method can be used to send ASCII as well as
binary data.
• The data sent by POST method goes through HTTP header
so security depends on HTTP protocol. By using Secure
HTTP you can make sure that your information is secure.
• The PHP provides $_POST associative array to access all the
sent information using POST method.
• Developers prefer POST for sending form data.

Prepared by Madam Amina


PHP $_REQUEST
• $_REQUEST is an associative array which we can use in
place of $_GET or $_POST.
• It means $_REQUEST is parent of $_GET and $_POST.
• $_REQUEST
– $_GET
– $_POST
• instead of using $_GET and $_POST we can use $_REQUEST.
• If $_REQUEST can perform working of $_GET and $_POST
both then why we use $_GET and $_POST separately.
• It is bad programming practice if we use always $_REQUEST
instead of $_GET and $_POST because it leads into
confusion of another developer that from where variable
value is coming.
• $_GET is dedicated to accept parameters from URL
• $_POST is dedicated to accept parameters through HTML
Prepared by Madam Amina
Summary
• As I said, these are just a few of the
superglobals available in PHP which I think
you’ll use the most $_GET and $_POST allow
your script to take in information from the
outside world.

Prepared by Madam Amina


The include() Function
• You can include the content of a PHP file into another
PHP file before the server executes it. There are two
PHP functions which can be used to included one PHP
file into another PHP file.
• The include() Function
• The require() Function
• This is a strong point of PHP which helps in creating
functions, headers, footers, or elements that can be
reused on multiple pages. This will help developers to
make it easy to change the layout of complete website
with minimal effort. If there is any change required
then instead of changing thousand of files just change
included file.

Prepared by Madam Amina


The include() Function

• The include() function takes all the text in a


specified file and copies it into the file that
uses the include function. If there is any
problem in loading a file then
the include() function generates a warning but
the script will continue execution.
• Assume you want to create a common menu
for your website. Then create a file menu.php
with the following content.

Prepared by Madam Amina


Cont.
• <a href=“index.htm">Home</a>
• <a href=“about.html">About Us</a>
• <a href=“Contact.html">Contact Us</a>
• Now create as many pages as you like and include
this file to create header. For example now your
test.php file can have following content.
• <html> <body>
• <?php
• include("menu.php"); ?>
• </body> </html>
Prepared by Madam Amina
The require() Function
• The require() function takes all the text in a
specified file and copies it into the file that uses
the require function. If there is any problem in
loading a file then the require() function
generates a fatal error and halt the execution of
the script.
• So there is no difference in require() and include()
except they handle error conditions. It is
recommended to use the require() function
instead of include(), because scripts should not
continue executing if files are missing or
misnamed.

Prepared by Madam Amina


Cont.
• You can try using above example with
require() function and it will generate same
result. But if you will try following two
examples where file does not exist then you
will get different results.
• So, if you want the execution to go on and
show users the output, even if the include file
is missing, use the include statement.

Prepared by Madam Amina


DATABASE
• A database is a collection of information that is organized so that it can be
easily accessed, managed and updated.
• collection of information organized to provide efficient retrieval. The
collected information could be in any number of formats ie electronic,
printed
• Database application
• A database application is a computer program whose primary purpose is
entering and retrieving information from a computerized database. Early
examples of database applications were accounting systems and airline
reservations systems, such as SABRE, developed starting in 1957.
• Different Types of Databases
a) Relational Databases
• This is the most common of all the different types of databases. In this,
the data in a relational database is stored in various data tables. Each table
has a key field which is used to connect it to other tables. Hence all the
tables are related to each other through several key fields. These
databases are extensively used in various industries and will be the one
you are most likely to come across when working in IT.

Prepared by Madam Amina


Cont.
• Examples of relational databases are Oracle, Sybase and Microsoft SQL
Server and they are often key parts of the process of software
development. Hence you should ensure you include any work required on
the database as part of your project when creating a project plan and
estimating project costs.
b) Operational Databases
• In its day to day operation, an organization generates a huge amount of
data. Think of things such as inventory management, purchases,
transactions and financials. All this data is collected in a database which is
often known by several names such as operational/ production database,
subject-area database (SADB) or transaction databases.
• An operational database is usually hugely important to Organisations as
they include the customer database, personal database and inventory
database ie the details of how much of a product the company has as well
as information on the customers who buy them. The data stored in
operational databases can be changed and manipulated depending on
what the company requires.

Prepared by Madam Amina


c) Database Warehouses
Cont.
• Organisations are required to keep all relevant data for several years. In the UK it
can be as long as 6 years. This data is also an important source of information for
analysing and comparing the current year data with that of the past years which
also makes it easier to determine key trends taking place. All this data from
previous years are stored in a database warehouse. Since the data stored has gone
through all kinds of screening, editing and integration it does not need any further
editing or alteration.
• With this database ensure that the software requirements specification (SRS) is
formally approved as part of the project quality plan.
d) Distributed Databases
• Many organisations have several office locations, manufacturing plants, regional
offices, branch offices and a head office at different geographic locations. Each of
these work groups may have their own database which together will form the
main database of the company. This is known as a distributed database.
e) End-User Databases
• There is a variety of data available at the workstation of all the end users of any
organisation. Each workstation is like a small database in itself which includes data
in spreadsheets, presentations, word files, note pads and downloaded files. All
such small databases form a different type of database called the end-user
database.

Prepared by Madam Amina


Advantages & Disadvantages
of Database
• Reduced data redundancy
• Reduced updating errors and increased consistency
• Greater data integrity and independence from applications programs
• Improved data access to users through use of host and query languages
• Improved data security
• Reduced data entry, storage, and retrieval costs
• Facilitated development of new applications program
• Disadvantages
• Database systems are complex, difficult, and time-consuming to design
• Substantial hardware and software start-up costs
• Damage to database affects virtually all applications programs
• Extensive conversion costs in moving form a file-based system to a
database system
• Initial training required for all programmers and users

Prepared by Madam Amina


database management system
• DBMS
• A database management system (DBMS) is system software for creating and managing databases.
... Many database management systems are also responsible for automated rollbacks, restarts and
recovery as well as the logging and auditing of activity.
• Interacts with end-users, other applications, and the database itself to capture and analyze data. A
general-purpose DBMS allows the definition, creation, querying, update, and administration of
databases
• TPYES OF DBMS
i. Oracle RDBMS
ii. Microsoft SQL Server
iii. MySQL
iv. Microsoft Access
v. IBM DB2
vi. Teradata
vii. PostgreSQL
viii. MongoDB
ix. SAP ASE (Sybase)
x. Informix

Prepared by Madam Amina


How websites work with databases
1. Websites like Google, Yahoo!, and Bing include a search dialog box
in which you enter a keyword that represents the subject matter
you are looking for. The search begins on a web page that includes
a form field to accept search items and HTML codes. Clicking the
search button sends a request from the browser to the web server
to bring back a list of all the websites that contain your keyword.
2. When you execute the search, the web server passes your search
information to a CGI script, which then searches the database. A
search on Google for soccer games would produce this
URL: https://www.google.ca/?gfe_rd=cr&ei=zNMtVNS-
I4fM8gfK5IDIAg#q=soccer+games
3. When the web server receives this URL, it identifies the URL as a
trigger for a CGI script and passes it along with the search criteria
("soccer games," in this example) to the miniprogram using CGI.
The CGI script then sends the search to the database.
4. The database retrieves the record or records that match the search
criteria and returns the data to the web server via CGI in a form of
a new HTML page. The server then sends the page back to the
client browser as a new HTML page.
Prepared by Madam Amina
INTRODUCTION TO MYSQLI
• MySQLi is improved version of MySQL. Before MySQLi we were using its
old version MySQL and millions number of projects have been developed
using PHP and MySQL and later PHP announce their ideas to deprecate
MySQL extension in 2011. Officially MySQL has been removed from PHP
5.5
• NOTE
• MySQLi database system is reliable for both small and large applications.
• MySQLi is open source relational database management system which is
used on web.
• MySQL must not be used in new development anymore.
• Old extension does not support Prepared Statements and improved
version of MySQL (MySQLi) and PDO that support Prepared Statements
are object oriented.
• For security reasons, you must use Prepared Statements. Its very
important for your web application security.
• By using Prepared Statements, you can protect your application from SQL
injection.
• MySQLi support for multiple statements and enhance debugging
capabilities.
Prepared by Madam Amina
Data Types
a) Numeric Data Types
• MySQLi uses all the standard ANSI SQL numeric data types, so if you're coming to
MySQLi from a different database system, these definitions will look familiar to
you. The following list shows the common numeric data types and their
descriptions −
• INT − A normal-sized integer that can be signed or unsigned. If signed, the
allowable range is from -2147483648 to 2147483647. If unsigned, the allowable
range is from 0 to 4294967295. You can specify a width of up to 11 digits.
• TINYINT − A very small integer that can be signed or unsigned. If signed, the
allowable range is from -128 to 127. If unsigned, the allowable range is from 0 to
255. You can specify a width of up to 4 digits.
• SMALLINT − A small integer that can be signed or unsigned. If signed, the
allowable range is from -32768 to 32767. If unsigned, the allowable range is from 0
to 65535. You can specify a width of up to 5 digits.
• MEDIUMINT − A medium-sized integer that can be signed or unsigned. If signed,
the allowable range is from -8388608 to 8388607. If unsigned, the allowable range
is from 0 to 16777215. You can specify a width of up to 9 digits.
• BIGINT − A large integer that can be signed or unsigned. If signed, the allowable
range is from -9223372036854775808 to 9223372036854775807. If unsigned, the
allowable range is from 0 to 18446744073709551615. You can specify a width of
up to 20 digits.

Prepared by Madam Amina


Cont.
• FLOAT(M,D) − A floating-point number that cannot be unsigned.
You can define the display length (M) and the number of decimals
(D). This is not required and will default to 10,2, where 2 is the
number of decimals and 10 is the total number of digits (including
decimals). Decimal precision can go to 24 places for a FLOAT.
• DOUBLE(M,D) − A double precision floating-point number that
cannot be unsigned. You can define the display length (M) and the
number of decimals (D). This is not required and will default to 16,4,
where 4 is the number of decimals. Decimal precision can go to 53
places for a DOUBLE. REAL is a synonym for DOUBLE.
• DECIMAL(M,D) − An unpacked floating-point number that cannot
be unsigned. In unpacked decimals, each decimal corresponds to
one byte. Defining the display length (M) and the number of
decimals (D) is required. NUMERIC is a synonym for DECIMAL.

Prepared by Madam Amina


Cont.
b) Date and Time Types
• The MySQL date and time datatypes are −
• DATE − A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For
example, December 30th, 1973 would be stored as 1973-12-30.
• DATETIME − A date and time combination in YYYY-MM-DD HH:MM:SS format,
between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the
afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00.
• TIMESTAMP − A timestamp between midnight, January 1, 1970 and sometime in
2037. This looks like the previous DATETIME format, only without the hyphens
between numbers; 3:30 in the afternoon on December 30th, 1973 would be
stored as 19731230153000 ( YYYYMMDDHHMMSS ).
• TIME − Stores the time in HH:MM:SS format.
• YEAR(M) − Stores a year in 2-digit or 4-digit format. If the length is specified as 2
(for example YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). If the length is
specified as 4, YEAR can be 1901 to 2155. The default length is 4.

Prepared by Madam Amina


Cont.
c) String Types
• Although numeric and date types are fun, most data you'll store will be in
string format. This list describes the common string datatypes in MySQLi.
• CHAR(M) − A fixed-length string between 1 and 255 characters in length
(for example CHAR(5)), right-padded with spaces to the specified length
when stored. Defining a length is not required, but the default is 1.
• VARCHAR(M) − A variable-length string between 1 and 255 characters in
length; for example VARCHAR(25). You must define a length when creating
a VARCHAR field.
• BLOB or TEXT − A field with a maximum length of 65535 characters. BLOBs
are "Binary Large Objects" and are used to store large amounts of binary
data, such as images or other types of files. Fields defined as TEXT also
hold large amounts of data; the difference between the two is that sorts
and comparisons on stored data are case sensitive on BLOBs and are not
case sensitive in TEXT fields. You do not specify a length with BLOB or
TEXT.

Prepared by Madam Amina


Cont.
• TINYBLOB or TINYTEXT − A BLOB or TEXT column with a maximum
length of 255 characters. You do not specify a length with TINYBLOB
or TINYTEXT.
• MEDIUMBLOB or MEDIUMTEXT − A BLOB or TEXT column with a
maximum length of 16777215 characters. You do not specify a
length with MEDIUMBLOB or MEDIUMTEXT.
• LONGBLOB or LONGTEXT − A BLOB or TEXT column with a
maximum length of 4294967295 characters. You do not specify a
length with LONGBLOB or LONGTEXT.
• ENUM − An enumeration, which is a fancy term for list. When
defining an ENUM, you are creating a list of items from which the
value must be selected (or it can be NULL). For example, if you
wanted your field to contain "A" or "B" or "C", you would define
your ENUM as ENUM ('A', 'B', 'C') and only those values (or NULL)
could ever populate that field.

Prepared by Madam Amina


Relational Database

• A Relational DataBase Management System (RDBMS) is a software


that −
• Enables you to implement a database with tables, columns and
indexes.
• Guarantees the Referential Integrity between rows of various
tables.
• Updates the indexes automatically.
• Interprets an SQL query and combines information from various
tables.
• MySQLi is a Relational SQL database management system. MySQLi
is used inside the PHP programming language to give an interface
with MySQL databases
• This is called relational database because all the data is stored into
different tables and relations are established using primary keys or
other keys known as foreign keys.

Prepared by Madam Amina


RDBMS Terminology
• Before we proceed to explain MySQLi database system, let's revise few definitions
related to database.
• Database − A database is a collection of tables, with related data.
• Table − A table is a matrix with data. A table in a database looks like a simple
spreadsheet.
• Column − One column (data element) contains data of one and the same kind, for
example the column postcode.
• Row − A row (= tuple, entry or record) is a group of related data, for example the
data of one subscription.
• Redundancy − Storing data twice, redundantly to make the system faster.
• Primary Key − A primary key is unique. A key value cannot occur twice in one
table. With a key, you can find at most one row.
• Foreign Key − A foreign key is the linking pin between two tables.
• Compound Key − A compound key (composite key) is a key that consists of
multiple columns, because one column is not sufficiently unique.
• Index − An index in a database resembles an index at the back of a book.
• Referential Integrity − Referential Integrity makes sure that a foreign key value
always points to an existing row.

Prepared by Madam Amina


MySQLi Connection using PHP Script
• PHP provides mysqli_connect() function to
open a database connection. This function
takes five parameters and returns a MySQLi
link identifier on success or FALSE on failure.
• Syntax
• connection
mysqli_connect(server,user,passwd,new_link,c
lient_flag);

Prepared by Madam Amina


Cont.
• server
• Optional - The host name running database server. If
not specified, then default value is localhost
• user
• Optional - The username accessing the database. If not
specified, then default is the name of the user that
owns the server process that is root
• passwd
• Optional - The password of the user accessing the
database. If not specified, then default is an empty
password.

Prepared by Madam Amina


How to connect to MySQL database
using PHP
<?php
/* Attempt MySQL server connection. Assuming you are
running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link ==false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
else echo "succefully connected";
?>

Prepared by Madam Amina


Create Database using PHP Script
• Creating the MySQL Database
• Since all tables are stored in a database, so first we
have to create a database before creating tables.
The CREATE DATABASE statement is used to create a
database in MySQL.
• Let's make a SQL query using the CREATE
DATABASE statement, after that we will execute this
SQL query through passing it to
the mysqli_query() function to finally create our
database.
• The mysqli_query() function performs a query against
the database.
• Syntax
• mysqli_query(connection,query)
Prepared by Madam Amina
The following example creates a database named “dit".
• <?php
• /* Attempt MySQL server connection. Assuming you are running
MySQLserver with default setting (user 'root' with no password) */
• $link = mysqli_connect("localhost", "root", "");
• //Check connection
• if($link == false)
• {
• die("ERROR: Could not connect. " );
• }
• // Attempt create database query execution
• $sql = "CREATE DATABASE dit";
• if(mysqli_query($link, $sql))
• {
• echo "Database dit created successfully";}
• else{
• echo "ERROR: Could not able to create database ";}
• ?>
Prepared by Madam Amina
Drop Database Using PHP Script
• PHP uses query function to create or delete a MySQLi database. This function takes two parameters
and returns TRUE on success or FALSE on failure.
• Example
• Try out the following example to delete a database −
• <?php
• $dbhost = 'localhost;
• $dbuser = 'root';
• $dbpass = “”
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass);
• if($conn == false){
• echo “Connected failure”; }
• Else{
• echo 'Connected successfully';
• }
• //SQL COMMAND TO DROP DATABASE TUTORIALS
• $sql = "DROP DATABASE TUTORIALS";
• if (mysqli_query($conn, $sql)) {
• echo "Record deleted successfully"; }
• else { echo "Error deleting record: " . mysqli_error($conn);
• }
• ?>

Prepared by Madam Amina


Cont.
• WARNING − While deleting a database using
PHP script, it does not prompt you for any
confirmation. So be careful while deleting a
MySQLi database.
• If connected and deleted database
successfully,then the sample output should be
like this −
• Connected successfullyDatabase deleted
successfully

Prepared by Madam Amina


MySQLi Creating Tables
• The table creation command requires −
• Name of the table
• Names of fields
• Definitions for each field
• Syntax
• Here is generic SQL syntax to create a MySQLi
table −
• CREATE TABLE table_name (column_name
column_type);

Prepared by Madam Amina


example
<?php
$host = 'localhost';
$user = 'root';
$pass = '‘”;
$dbname = 'TUTORIALS';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if($conn==false){
die('Could not connect: '.mysqli_connect_error());
}
Else{
echo 'Connected successfully';
}
//SQL COMMAND TO CREATE TABLE tutorials_inf
$sql = "create table tutorials_inf( id INT AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(20) NOT NULL, )”;
if(mysqli_query($conn, $sql)){
echo "Table created successfully"; }
else {
echo "Table is not created successfully "; }
?>
Prepared by Madam Amina
Here few items need explanation −

• Field Attribute NOT NULL is being used because


we do not want this field to be NULL. So if user
will try to create a record with NULL value, then
MySQLi will raise an error.
• Field Attribute AUTO_INCREMENT tells MySQLi
to go ahead and add the next available number to
the id field.
• Keyword PRIMARY KEY is used to define a
column as primary key. You can use multiple
columns separated by comma to define a primary
key.

Prepared by Madam Amina


Dropping Tables Using PHP Script
• To drop an existing table in any database, you would need to use PHP function
mysqli_query(). You will pass its second argument with proper SQL command to drop a table.
• Example
• <?php
• $host = 'localhost';
• $user = 'root';
• $pass = '‘”;
• $dbname = 'TUTORIALS';
• $conn = mysqli_connect($host, $user, $pass,$dbname);
• if($conn==false) {
• die('Could not connect: '.mysqli_connect_error()); }
• else{
• echo 'Connected successfully';
• }
• //SQL COMMAND TO DROP TABLE tutorials _inf
• $sql = "DROP TABLE tutorials_inf";
• if(mysqli_query($conn, $sql)) {
• echo "Table is deleted successfully"; }
• else {
• echo "Table is not deleted successfully"; }
Prepared by Madam Amina
• ?>
Inserting Data Using PHP Script
• You can use same SQL INSERT INTO command
into PHP function mysqli_query() to insert
data into a MySQLi table.

Prepared by Madam Amina


example
• <?php
• $link = mysqli_connect("localhost", "root", "",
“TUTORIALS");
• // Check connection
• if($link == false){
• die("ERROR: Could not connect. " );}
• // Attempt insert query execution
• $sql = "INSERT INTO tutorials_inf (id, name ) VALUES (24,
'amina')";
• if(mysqli_query($link, $sql)){
• echo "Records added successfully.";}
• else{ echo "ERROR: Could not able to execute " ;}
• ?>

Prepared by Madam Amina


Insert Data Into a Database From an
HTML Form
• Let's create an HTML form that can be used to
insert new records to persons table.
• Creating the HTML Form
• Here's a simple HTML form that has three
text <input> fileds and a submit button.

Prepared by Madam Amina


• <html> <head>
Cont.
<title>Add New Record in MySQLi Database</title>
• </head> <body>
• <div id = "main">
• <form action = "" method = "post">
• <label>Name :</label>
• <input type = "text" name = "name" id = "name" /> <br />
<br /> <input type = "submit" value ="Submit" name = "submit"/>
<br /> </form>
• </div>
• <?php
• if(isset($_POST["submit"])){
• $servername = "localhost";
• $username = "root";
• $password = “”;
• $dbname = "TUTORIALS";
• // Create connection
• $conn = mysqli_connect($servername, $username, $password,
$dbname);

Prepared by Madam Amina


Cont--
• // Check connection
• if ($conn== false) {
• die("Connection failed: " . $conn->connect_error);
• }
• $a=$_POST[‘name’];
• $sql = "INSERT INTO tutorials_inf(name)VALUES (‘$a’)”;
• if (mysqli_query($conn, $sql)) {
• echo "New record created successfully";
• } else {
• echo "Error: " . $sql . "" . mysqli_error($conn);
• }
• $conn->close(); }
• ?>
• </body></html>

Prepared by Madam Amina


Example
• <!DOCTYPE html>
• <html>
• <head><title>Add Record Form</title></head>
• <body>
• <form action="insert.php" method="post">
• <input type="text" name="firstname" placeholder ="enter first
name"/> <br/>
• <input type="text" name="lastname" placeholder ="enter last
name"/><br>
• <input type="email" name="email" placeholder ="enter your
email"><br>
• <input type="submit" value="SEND">
• </form>
• </body>
• </html>

Prepared by Madam Amina


Fetching Data Using PHP Script

• You can use same SQL SELECT command into PHP


function mysqli_query(). This function is used to
execute SQL command and later another PHP
function mysqli_fetch_assoc() can be used to
fetch all the selected data. This function returns
row as an associative array, a numeric array, or
both. This function returns FALSE if there are no
more rows.
• Below is a simple example to fetch records from
tutorials_inf table.

Prepared by Madam Amina


Example
Try out the following example to display all the records from

• <html> <head>
tutorials_inf table .
<title>Selecting Table in MySQLi Server</title>
</head> <body>
• <?php
• $conn = mysqli_connect(“localhost”,”root”,””,”TUTORIALS”); if(!
$conn ) {
• die('Could not connect: ' . mysqli_error());
• }
• echo 'Connected successfully<br>';
• $sql = 'SELECT name FROM tutorials_inf';
• $result = mysqli_query($conn, $sql);
• if (mysqli_num_rows($result) > 0) {
• while($row = mysqli_fetch_assoc($result)) {
• echo "Name: " . $row["name"]. "<br>"; }
• } else { echo "0 results"; }
• mysqli_close($conn);
• ?>
• </body></html>
Prepared by Madam Amina
Fetching Data Using PHP Script:

• You can use same SQL SELECT command with


WHERE CLAUSE into PHP function
mysqli_query().
• Example
• Following example will return all the records
from tutorials_inf table for which name is sai

Prepared by Madam Amina


EXAMPLE
• <?php
• $conn = mysqli_connect(“localhost”, “root”,””,”TUTORIALS”);

• if(! $conn ) {
• die('Could not connect: ' . mysqli_error());
• }
• echo 'Connected successfully<br>';
• $sql = 'SELECT * from tutorials_inf where first_name=“amina"';
• $result = mysqli_query($conn, $sql);

• if (mysqli_num_rows($result) > 0) {
• while($row = mysqli_fetch_assoc($result)) {
• echo "Name: " . $row["first_name"]." ". $row["last_name"]." ".
$row["email_address"]."<br>";
• }
• } else {
• echo "0 results";
• }
• mysqli_close($conn);
• ?>
Prepared by Madam Amina
Updating Data Using PHP Script

• You can use SQL UPDATE command with or


without WHERE CLAUSE into PHP function
mysqli_query(). This function will execute SQL
command in similar way it is executed at
mysql> prompt.

Prepared by Madam Amina


example
• Try out the following example to update name field for a record.
• <?php
• $dbhost = 'localhost';
• $dbuser = 'root';
• $dbpass = '';
• $dbname = 'dit';
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
• if(! $conn ) {
• die('Could not connect: ' . mysqli_error());
• }
• echo 'Connected successfully<br>';
• $sql = ' UPDATE tutorials_inf SET name="althamas" WHERE name="ASHA"';
• if (mysqli_query($conn, $sql)) {
• echo "Record updated successfully";
• } else {
• echo "Error updating record: " . mysqli_error($conn);
• }
• mysqli_close($conn);
• ?>

Prepared by Madam Amina


Deleting Data Using PHP Script
• You can use SQL DELETE command with or
without WHERE CLAUSE into PHP function
mysqli_query(). This function will execute SQL
command in similar way it is executed at
mysql> prompt.

Prepared by Madam Amina


example
• <?php
• $dbhost = 'localhost:3306';
• $dbuser = 'root';
• $dbpass = '';
• $dbname = 'dit';
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);

• if(! $conn ) {
• die('Could not connect: ' . mysqli_error());
• }
• echo 'Connected successfully<br>';
• $sql = ' DELETE FROM tutorials_inf WHERE name = "amina"';

• if (mysqli_query($conn, $sql)) {
• echo "Record deleted successfully";
• } else {
• echo "Error deleting record: " . mysqli_error($conn);
• }
• mysqli_close($conn);
• ?>
Prepared by Madam Amina
MySQLi - Sorting Results
• Syntax
• Here is generic SQL syntax of SELECT command along with ORDER
BY clause to sort data from MySQL table −
• SELECT field1, field2,...fieldN table_name1, table_name2...ORDER
BY field1, [field2...] [ASC [DESC]] You can sort returned result on any
field provided that filed is being listed out.
• You can sort result on more than one field.
• You can use keyword ASC or DESC to get result in ascending or
descending order. By default, it's ascending order.
• You can use WHERE...LIKE clause in usual way to put condition.
• Using ORDER BY clause inside PHP Script
• You can use similar syntax of ORDER BY clause into PHP function
mysqli_query(). This function is used to execute SQL command and
later another PHP function mysqli_fetch_array() can be used to
fetch all the selected data.

Prepared by Madam Amina


example
• <?php
• $dbhost = 'localhost:3306';
• $dbuser = 'root';
• $dbpass = '';
• $dbname = 'dit';
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);

• if(! $conn ) {
• die('Could not connect: ' . mysqli_error());
• }
• echo 'Connected successfully</br>';
• $sql = 'SELECT * from persons ORDER BY first_name ';

• if($result = mysqli_query($conn, $sql)){
• if(mysqli_num_rows($result) > 0){
• echo "<table>";
• echo "<tr>";
• echo "<th>first name</th>";
• echo "<th>last name</th>";
• echo "</tr>";
Prepared by Madam Amina

Cont.
• while($row = mysqli_fetch_array($result)){
• echo "<tr>";
• echo "<td>" . $row['first_name'] . "</td>";
• echo "<td>" . $row['last_name'] . "</td>";
• echo "</tr>";
• }
• echo "</table>";
• mysqli_free_result($result);
• }

• else {
• echo "No records matching your query were found.";
• }
• } else {
• echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
• }
• mysqli_close($conn);
• ?>

Prepared by Madam Amina


MySQLi - ALTER Command

• MySQLi ALTER command is very useful when


you want to change a name of your table, any
table field or if you want to add or delete an
existing column in a table.

Prepared by Madam Amina


A. Dropping, Adding or Repositioning a Column
• Suppose you want to drop an existing column i from above MySQLi table then you will use DROP
clause along with ALTER command as follows −
• <?php
• $dbhost = 'localhost:3306';
• $dbuser = 'root';
• $dbpass = '';
• $dbname = 'dit';
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
• if(!$conn){
• echo "not connected";
• }
• $drop_column = "ALTER TABLE persons DROP email_address";
• if(mysqli_query($conn,$drop_column))
• {
• echo "droped column";
• }
• else{
• echo "fail";
• }
• ?>
• NOTE: A DROP will not work if the column is the only one left in the table.

Prepared by Madam Amina


To add a column
• To add a column, use ADD and specify the
column definition. The following statement
restores the i column to tutorials_info −

Prepared by Madam Amina


example
• <?php
• $dbhost = 'localhost:3306';
• $dbuser = 'root';
• $dbpass = '';
• $dbname = 'dit';
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
• if(!$conn){
• echo "not connected";
• }

• $drop_column = "ALTER TABLE persons ADD email_address VARCHAR(10)";
• if(mysqli_query($conn,$drop_column))
• {
• echo "COLUMN ADDED";
• }
• else{
• echo "fail";
• }
• ?>

Prepared by Madam Amina


Repositioning a Column
• To indicate that you want a column at a specific position
within the table, either use FIRST to make it the first
column or AFTER col_name to indicate that the new
column should be placed after col_name. Try the following
ALTER TABLE statements, using SHOW COLUMNS after each
one to see what effect each one has −
• ALTER TABLE testalter_tbl DROP i;ALTER TABLE testalter_tbl
ADD i INT FIRST;ALTER TABLE testalter_tbl DROP i;ALTER
TABLE testalter_tbl ADD i INT AFTER c;
• The FIRST and AFTER specifiers work only with the ADD
clause. This means that if you want to reposition an existing
column within a table, you first must DROP it and then ADD
it at the new position.

Prepared by Madam Amina


Changing a Column Definition or Name

• To change a column's definition, use MODIFY


or CHANGE clause along with ALTER
command. For example, to change column c
from CHAR(1) to CHAR(10), do this −
• ALTER TABLE tutorials_alter MODIFY c
CHAR(10);

Prepared by Madam Amina


Cont.
• With CHANGE, the syntax is a bit different. After
the CHANGE keyword, you name the column you
want to change, then specify the new definition,
which includes the new name. Try out the
following example:
• mysql> ALTER TABLE tutorials_alter CHANGE i j
BIGINT; If you now use CHANGE to convert j from
BIGINT back to INT without changing the column
name, the statement will be as expected −
• mysql> ALTER TABLE tutorials_alter CHANGE j j
INT;

Prepared by Madam Amina


HOW TO LOGIN
• <HTML>
• <HEAD>
• <TITLE>Login Page </TITLE>
• </HEAD>
• <BODY>
• <form action="login.php" method="POST">
• <input type="text" name="username" placeholder="Enter
username">
• <input type="password" name="password" placeholder="Enter
Password">
• <input type="submit" value="Submit">
• </form>
• </BODY>
• </HTML>

Prepared by Madam Amina


Sample code
• <?php
• $con = mysqli_connect(“localhost”,”root”,””,TUTORIALS”) or die("not
connect");
• $username = &$_POST["username"];
• $password = &$_POST["password"];
• $table = “persons";
• $result = ("SELECT * FROM $table WHERE first_name='$username'
AND password='$password'") or die($con->error);
• $rows = mysqli_num_rows($result);
• if($rows>0){
• //Redirect
• header("Location:any_file.php");
• echo "Success";
• }
• else{
• header("Location:index.php");
• }
• ?> Prepared by Madam Amina
Cont.
• NOTE:-
• We can use header() function for redirection
of pages like this :-
header("location:index.php");

Prepared by Madam Amina


Create Database and Table using MySQL
• Php my admin is for creating the MySQL
database
• Below are steps for creating database by using
phpmyadmin:-
• STEP 1:-Once the browser opens the
phpmyadmin page, Enter the database name
inside “create new database” field and click
create button. For this tutorial we using
database name as “user”.

Prepared by Madam Amina


Cont.

Prepared by Madam Amina


Cont.
• After the database created, click the SQL link
from the top menu and paste the following sql
query into the text area and click go button
below the textarea.

Prepared by Madam Amina


Cont.

Prepared by Madam Amina


Cont.
• Click the insert link for login table and give sample user name
and password and click go button

Prepared by Madam Amina


Cont.
• After the sample user data inserted, table will
show the data like below image.

Prepared by Madam Amina


Cont.
• STEP2: Connect the MySQL database using PHP
• Create config.php file and paste the following code to the
file.
• <?php
• define("DB_HOST","localhost");
• define("DB_USER","root");
• define("DB_PASSWORD","");
• define("DB_DATABASE","dit");
• $con = new
mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE)o
r die("not connect");
• ?>

Prepared by Madam Amina


Cont.
• Hostname : It specifies system host name or
system ip address. The default value is
localhost
• User: mysql username. Default value is root.
• Password: mysql password
• Mysql_Database : mysql database name

Prepared by Madam Amina


Cont.
• STEP 3:-create index.php form. Paste the
following code
• <!DOCTYPE html>
• <html>
• <head>
• <title></title>
• </head>
• <body>
• <table align="center" bgcolor="#CCCCCC" border="0" cellpadding="0"
• cellspacing="1" width="300">
• <tr>
• <td>

Prepared by Madam Amina


cont.

• <form method="post" name="" action="login.php">


• <table bgcolor="#FFFFFF" border="0" cellpadding="3"
• cellspacing="1" width="100%">
• <tr>
• <td align="center" colspan="3"><strong>User
• Login</strong></td>
• </tr>
• <tr>
• <td width="78">Username</td>
• <td width="6">:</td>
• <td width="294"><input id="username" name=
• "username" type="text"></td>
• </tr>
Prepared by Madam Amina
Cont.
• <tr>
• <td>Password</td>
• <td>:</td>
• <td><input id="password" name="password" type=
• "password"></td>
• </tr>
• <tr>
• <td>&nbsp;</td>
• <td>&nbsp;</td>
• <td><input name="submit" type="submit" value=
• "Login"> <input name="reset" type="reset" value=
• "reset"></td>
• </tr>
• </table>
• </form>
• </td>
• </tr>
• </table>
• </body></html>

Prepared by Madam Amina


cont.
• STEP 4: Create the Login page
• Create login.php file and copy past the below
code to the file.
• Following code has the login form and to get
posted value after the form submitted using
$_POST.

Prepared by Madam Amina


Cont.
• <?php
• include("config.php");
• $username = &$_POST["username"];
• $password = &$_POST["password"];
• $table = "info";
• $result=$con->query("SELECT * FROM $table WHERE first_name='$username'
AND password='$password'") or die($con->error);
• $rows = mysqli_num_rows($result);
• if($rows>0){
• //Redirect
• header("Location:home1.php");
• echo "Success";
• }
• else
• {
• echo "<script type='text/javascript'>alert('User Name Or Password
Invalid!')</script>";
• }
• //echo $username."<br>";
• //echo $password;
• ?>
Prepared by Madam Amina
Cont.
• Post Method: We used post method to get the values,
because post method is secure way to pass the username
and password. Post method is the best practice when we
passing the secure data’s.
• Include the config.php in login.php to connect the
database:Using php “include()” function include the
config.php in login.php.
• Session:Session is used to start the session and store the
values in session and get the values anywhere in the web
pages. To start the session, call the session_start() function
in login.php file.
• Mysqli_Num_Rows: Mysql_Num_Rows function is used to
return a number of rows from the table

Prepared by Madam Amina


cont
• Step 5: Create home1.php
• Create the home1.php file which has the script to
destroy the session. When a user submit their
username and password in login page, php login
script will check the given username and
password in the database table using MySQL
select query, if the query return the value, script
will redirect to home.php page. If username or
password is wrong system will show error
message as “User Name Or Password Invalid”.

Prepared by Madam Amina


Home1.php file
• <html>
• <body>

• WELCOME</br>
• <a href="logout.php"> logout</a>

• </body>
• </html>

Prepared by Madam Amina


Cont.
• Step 6: Destroy the session once the user
clicks the logout link from home.php page
• Create the logout.php file and paste the below
code in to the logout.php file. Logout will
destroy the session and redirect to login.php
page again.

Prepared by Madam Amina


Logout.php file
• <?php
• session_start();
• if(session_destroy())
• {
• header("Location: index.php");
• }
• ?>

Prepared by Madam Amina

Вам также может понравиться