Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

unit-v-php-mc4023-web-design-lecture-notes

Uploaded by

akssatheesh16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

unit-v-php-mc4023-web-design-lecture-notes

Uploaded by

akssatheesh16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

lOMoARcPSD|22700398

UNIT V PHP - mc4023 web design lecture notes

web design (Anna University)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)
lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

UNIT V SERVER-SIDE PROGRAMMING WITH PHP


PHP basic syntax-PHP Variables and basic data structures-Using PHP to manage form submissions-
File Handling -Cookies and Sessions with PHP-Working with WAMP and PHPMYADMIN-
Establishing connectivity with MySQL using PHP

PHP | Basic Syntax


The structure which defines PHP computer language is called PHP syntax.
The PHP script is executed on the server and the HTML result is sent to the browser. It can
normally have HTML and PHP tags. PHP or Hypertext Preprocessor is a widely used open-
source general-purpose scripting language and can be embedded with HTML. PHP files are
saved with the “.php” extension. PHP scripts can be written anywhere in the document within
PHP tags along with normal HTML
Canonical PHP Tags: The script starts with <?php and ends with ?>. These tags are also
called ‘Canonical PHP tags’. Everything outside of a pair of opening and closing tags is
ignored by the PHP parser. The open and closing tags are called delimiters. Every PHP
command ends with a semi-colon (;). Let’s look at the hello world program in PHP.
Syntax:
<?php
# Here echo command is used to print
//stmt. Ends with semicolon;
echo "Hello, world!";
?>
OUTPUT:
Hello, world!
Comments in PHP:
Comments help in reminding the developer about the code if it’s re-visited after a
period of time.
A comment is something that is ignored and not read or executed by the PHP engine
or the language as part of a program and is written to make the code more readable and
understandable. These are used to help other users and developers to describe the code and
what it is trying to do. It can also be used in documenting a set of codes or parts of a
program. You must have noticed this in the above sample programs.
PHP supports two types of comment:

 Single Line Comment: As the name suggests these are single line or short
relevant explanations that one can add to their code. To add this, we need to
begin the line with (//) or (#).
 Multi-line or Multiple line Comment: These are used to accommodate multiple
lines with a single tag and can be extended to many lines as required by the user.
To add this, we need to begin and end the line with (/*…*/)

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 1

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

PHP is case-sensitive. All the keywords, functions, and class names in PHP (while, if, echo,
else, etc) are NOT case-sensitive except variables. Only variables with different cases are
treated differently.
EX:
<?php
// Here we can see that all echo
// statements are executed in the same manner

$variable = 25;
echo $variable;
ECHO $variable;
EcHo $variable;

// but this line will show RUNTIME ERROR as


// "Undefined Variable"
echo $VARIABLE
?>

PHP | Variables and data structure

Variables in a program are used to store some values or data that can be used later in a
program. The variables are also like containers that store character values, numeric values,
memory addresses, and strings. PHP has its own way of declaring and storing variables.
There are few rules, that needs to be followed and facts that need to be kept in mind while
dealing with variables in PHP:
 Any variables declared in PHP must begin with a dollar sign ($), followed by the
variable name.
 A variable can have long descriptive names (like $factorial, $even_nos) or short
names (like $n or $f or $x)
 A variable name can only contain alphanumeric characters and underscores (i.e.,
‘a-z’, ‘A-Z’, ‘0-9 and ‘_’) in their name. Even it cannot start with a number.
 A constant is used as a variable for a simple value that cannot be changed. It is
also case-sensitive.
 Assignment of variables is done with the assignment operator, “equal to (=)”. The
variable names are on the left of equal and the expression or values are to the right
of the assignment operator ‘=’.
 One must keep in mind that variable names in PHP names must start with a letter
or underscore and no numbers.
 PHP is a loosely typed language, and we do not require to declare the data types
of variables, rather PHP assumes it automatically by analyzing the values. The

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 2

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

same happens while conversion. No variables are declared before they are used. It
automatically converts types from one type to another whenever required.
 PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.
Data types used by PHP to declare or construct variables:
 Integers
 Doubles
 NULL
 Strings
 Booleans
 Arrays
 Objects
 Resources
Example:

 PHP

<?php

// These are all valid declarations


$val = 5;
$val2 = 2;
$x_Y = "gfg";
$_X = "GeeksforGeeks";

// This is an invalid declaration as it


// begins with a number
$10_ val = 56;

// This is also invalid as it contains


// special character other than _
$f.d = "num";

?>

Local variables: The variables declared within a function are called local variables to that
function and has its scope only in that particular function. In simple words, it cannot be
accessed outside that function. Any declaration of a variable outside the function with same
name as that of the one within the function is a complete different variable.
Global variables: The variables declared outside a function are called global variables.
These variables can be accessed directly outside a function. To get access within a function
we need to use the “global” keyword before the variable to refer to the global variable.

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 3

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

Using PHP to manage form submissions


What is Form?
When you login into a website or into your mail box, you are interacting with a form.

Forms are used to get input from the user and submit it to the web server for processing.

The diagram below illustrates the form handling process.

A form is an HTML tag that contains graphical user interface items such as input box, check
boxes radio buttons etc.

The form is defined using the <form>…</form> tags and GUI items are defined using form
elements such as input.

When and why we are using forms?

 Forms come in handy when developing flexible and dynamic applications that accept
user input.
 Forms can be used to edit already existing data from the database

Create a form
We will use HTML tags to create a form. Below is the minimal list of things you need to
create a form.

 Opening and closing form tags <form>…</form>


 Form submission type POST or GET
 Submission URL that will process the submitted data
 Input fields such as input boxes, text areas, buttons,checkboxes etc.

<html>
<head>
<title>Registration Form</title>

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 4

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


</head>
<body>

<h2>Registration Form</h2>

<form action="registration_form.php" method="POST"> First name:

<input type="text" name="firstname"> <br> Last name:

<input type="text" name="lastname">

<input type="hidden" name="form_submitted" value="1" />

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

</form>
</body>
</html>

Viewing the above code in a web browser displays the following form.

HERE,

 <form…>…</form> are the opening and closing form tags


 action=”registration_form.php” method=”POST”> specifies the destination URL and
the submission type.
 First/Last name: are labels for the input boxes
 <input type=”text”…> are input box tags
 <br> is the new line tag
 <input type=”hidden” name=”form_submitted” value=”1″/> is a hidden value that is
used to check whether the form has been submitted or not
 <input type=”submit” value=”Submit”> is the button that when clicked submits the
form to the server for processing

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 5

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

Submitting the form data to the server


The action attribute of the form specifies the submission URL that processes the data. The
method attribute specifies the submission type.

PHP POST method

 This is the built in PHP super global array variable that is used to get values submitted
via HTTP POST method.
 The array variable can be accessed from any script in the program; it has a global
scope.
 This method is ideal when you do not want to display the form post values in the
URL.
 A good example of using post method is when submitting login details to the server.

It has the following syntax.

<?php
$_POST['variable_name'];
?>
HERE,

 “$_POST[…]” is the PHP array


 “’variable_name’” is the URL variable name.

PHP GET method

 This is the built in PHP super global array variable that is used to get values submitted
via HTTP GET method.
 The array variable can be accessed from any script in the program; it has a global
scope.
 This method displays the form values in the URL.
 It’s ideal for search engine forms as it allows the users to book mark the results.

It has the following syntax.

 <?php
 $_GET['variable_name'];
 ?>
HERE,

 “$_GET[…]” is the PHP array


 “’variable_name’” is the URL variable name.

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 6

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

GET vs POST Methods


POST GET

1.Values not visible in the URL Values visible in the URL

2. Has not limitation of the length of the Has limitation on the length of the values usually 255
values since they are submitted via the characters. This is because the values are displayed in
body of HTTP the URL. Note the upper limit of the characters is
dependent on the browser.

3. Has lower performance compared to Has high performance compared to POST method
Php_GET method due to time spent dues to the simple nature of appending the values in
encapsulation the Php_POST values in the URL.
the HTTP body

4. Supports many different data types Supports only string data types because the values are
such as string, numeric, binary etc. displayed in the URL

5. Results cannot be book marked Results can be book marked due to the visibility of
the values in the URL

The below diagram shows the difference between get and post

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 7

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

PHP | Basics of File Handling


File handling is needed for any application. For some tasks to be done file needs to
be processed. File handling in PHP is similar as file handling is done by using any
programming language like C. PHP has many functions to work with normal files. Those
functions are:
1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen() contains
name of the file which is to be opened and second parameter tells about mode in which file
needs to be opened, e.g.,
Ex:

<?php

$file = fopen(“demo.txt”,'w');

?>

Files can be opened in any of the following modes :


 “w” – Opens a file for write only. If file not exist then new file is created and if
file already exists then contents of file is erased.
 “r” – File is opened for read only.
 “a” – File is opened for write only. File pointer points to end of file. Existing
data in file is preserved.
 “w+” – Opens file for read and write. If file not exist then new file is created and
if file already exists then contents of file is erased.
 “r+” – File is opened for read/write.
 “a+” – File is opened for write/read. File pointer points to end of file. Existing
data in file is preserved. If file is not there then new file is created.
 “x” – New file is created for write only.
2) fread() –– After file is opened using fopen() the contents of data are read using fread().
It takes two arguments. One is file pointer and another is file size in bytes, e.g.,

<?php
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 8

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

$filedata = fread( $file, $size );


?>

3) fwrite() – New file can be created or text can be appended to an existing file using
fwrite() function. Arguments for fwrite() function are file pointer and text that is to written
to file. It can contain optional third argument where length of text to written is specified,
e.g.,

<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>

4) fclose() – file is closed using fclose() function. Its argument is file which needs to be
closed, e.g.,

<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>

PHP Cookies
A cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the
client computer. They are typically used to keep track of information such as a username that the site can
retrieve to personalize the page when the user visits the website next time. A cookie can only be read
from the domain that it has been issued from. Cookies are usually set in an HTTP header but JavaScript
can also set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The setcookie()
function needs to be called prior to any output generated by the script otherwise the cookie will not be
set.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general which are:

 Name: It is used to set the name of the cookie.


 Value: It is used to set the value of the cookie.
 Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be
accessed.
 Path: It is used to specify the path on the server for which the cookie will be available.
 Domain: It is used to specify the domain for which the cookie is available.

 Security: It is used to indicate that the cookie should be sent only if a secure HTTPS
connection exists.
Below are some operations that can be performed on Cookies in PHP:
Creating Cookies: Creating a cookie named Auction_Item and assigning the value Luxury
Car to it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 9

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created."
?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>

</body>
</html>

Note: Only the name argument in the setcookie() function is mandatory. To skip an
argument, the argument can be replaced by an empty string(“”).
Output:

Deleting Cookies: The setcookie() function can be used to delete a cookie. For deleting a
cookie, the setcookie() function is called by passing the cookie name and other arguments
or empty strings but however this time, the expiration date is required to be set in the past.
To delete a cookie named “Auction_Item”, the following code can be executed.

PHP | Sessions
What is a session?
In general, session refers to a frame of communication between two medium. A PHP session
is used to store data on a server rather than the computer of the user. Session identifiers or SID
is a unique number which is used to identify every user in a session based environment. The
SID is used to link the user with his information on the server like posts, emails etc
Although cookies are also used for storing user related data, they have serious security
issues because cookies are stored on the user’s computer and thus they are open to attackers

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 10

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

to easily modify the content of the cookie.Addition of harmful data by the attackers in the
cookie may result in the breakdown of the application.

Apart from that cookies affect the performance of a site since cookies send the user data each
time the user views a page.Every time the browser requests a URL to the server, all the cookie
data for that website is automatically sent to the server within the request.

Below are different steps involved in PHP sessions:


 Starting a PHP Session: The first step is to start up a session. After a session is
started, session variables can be created to store information. The
PHP session_start() function is used to begin a new session.It als creates a new
session ID for the user.
Below is the PHP code to start a new session:

<?php

session_start();

?>

 Storing Session Data: Session data in key-value pairs using


the $_SESSION[] superglobal array.The stored data can be accessed during
lifetime of a session.
Below is the PHP code to store a session with two session variables Rollnumber
and Name:

<?php

session_start();

$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";

?>

 Accessing Session Data: Data stored in sessions can be easily accessed by


firstly calling session_start() and then by passing the corresponding key to
the $_SESSION associative array.
The PHP code to access a session data with two session variables Rollnumber
and Name is shown below:

<?php

session_start();

echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>';

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 11

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>';

?>

Output:
The Name of the student is :Ajay
The Roll number of the student is :11
Destroying Certain Session Data: To delete only a certain session data,the
unset feature can be used with the corresponding session variable in
the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the associative session
array:

<?php

session_start();

if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
}

?>

WORKING WITH WAMP

What Is WAMP
WAMP is an acronym that stands for Windows, Apache, MySQL, and PHP. It’s a software

stack which means installing WAMP installs Apache, MySQL, and PHP on your operating system
(Windows in the case of WAMP). Even though you can install them separately, they are usually

bundled up, and for a good reason too.

PHP Server installation (Wamp Server)


As we already know that php is a server side scripting language so we need server to run php code.
There are many servers to run php program. If you are using Windows Operating System then you can
install WMAP server which stands for Windows Apache MySql and PHP or Perl or python. It is a
complete package or stack. And if you are using Linux Operating System then you can install Lamp which
stands for Linux Apache MySql and PHP or Perl or python. .
Here I am using WAMP server. When you installed WAMP server you will get wamp folder in
your C drive. In this folder there is another folder name www. To run php code we have to put all php files
in this folder. Php files having .php extension. We can use Notepad or Notepad++ to create .php files.

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 12

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

How to run php files using wamp server?

Let me explain today how to use the wamp server to run the PHP files. First of all download the Latest
wamp server from here:
http://www.wampserver.com/
and install the server.
Step 2:
Run wamp server by this selction
start->All programs->Wamp server->Start wamp server

Now you can see the w icon in system tray.

Step 3: Create PHP file


Let us create our php file first.
Open notepad and type the php code.
save the file inside this folder
c://wamp/www/
also you can create folder inside this folder to more specific.

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 13

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

Note: while saving the file, end the name with .php and don’t forget to select all files.
Let us assume i have stored Testing.php
Step 4: Start the server
Left click on the wamp icon in system tray.
It will display list of options.
Select “start all services”.

Step 5:Run
Now all services(especially php) is running.
Open the mozilla and type localhost in address bar.
Hit enter
It will show the default page of wamp server.
Now include this Testing.php (my php file name) at the end of the url

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 14

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

For ex:
http://localhost/Testing.php
It will run your php file.

WORKING WITH phpMyAdmin

phpMyAdmin is an open-source software tool introduced on September 9, 1998, which is written in


PHP. Basically, it is a third-party tool to manage the tables and data inside the database. phpMyAdmin
supports various type of operations on MariaDB and MySQL. The main purpose of phpMyAdmin is to
handle the administration of MySQL over the web.

It is the most popular application for MySQL database management. We can create, update, drop,
alter, delete, import, and export MySQL database tables by using this software. phpMyAdmin also supports
a wide range of operation like managing databases, relations, tables, columns, indexes, permissions,
and users, etc., on MySQL and MariaDB. These operations can be performed via user interface, while we
still have the ability to execute any SQL statement.

phpMyAdmin is translated into 72 languages and also supports both RTL and LTR languages so
that the wide range of people can easily use this software. We can run MySQL queries, repair, optimized,
check tables, and also execute other database management commands. phpMyAdmin can also be used to
perform administrative tasks such as database creation, query execution.

phpMyAdmin is a GUI-based application which is used to manage MySQL database. We can


manually create database and table and execute the query on them. It provides a web-based interface and
can run on any server. Since it is web-based, so we can access it from any computer.

Features of phpMyAdmin

phpMyAdmin supports several features that are given below:

o phpMyAdmin can create, alter, browse, and drop databases, views, tables, columns, and indexes.
o It can display multiple results sets through queries and stored procedures.
o phpMyAdmin use stored procedure and queries to display multiple results sets.
o It supports foreign keys and InnoDB tables.
o phpMyAdmin can track the changes done on databases, views, and tables.
o We can also create PDF graphics of our database layout.
o phpMyAdmin can be exported into various formats such as XML, CSV, PDF, ISO/IEC 26300 -
OpenDocument Text and Spreadsheet.
o It supports mysqli, which is the improved MySQL extension.
o phpMyAdmin can interact with 80 different languages.
o phpMyAdmin can edit, execute, and bookmark any SQL-statements and even batch-queries.
o By using a set of pre-defined functions, it can transform stored data into any format. For example -
BLOB-data as image or download-link.
Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 15

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

o It provides the facility to backup the database into different forms.

Advantage of phpMyAdmin
o phpMyAdmin can run on any server or any OS as it has a web browser.
o We can easily create, delete, and edit the database and can manage all elements using the graphical
interface of phpMyAdmin, which is much easier than MySQL command-line editor.
o phpMyAdmin helps us to control the user's permission and operate several servers at the same time.
o We can also backup our database and export the data into different formats like XML, CSV, SQL,
PDF, OpenDocument Text, Excel, Word, and Spreadsheet, etc.
o We can execute complex SQL statements and queries, create and edit functions, triggers, and events
using the graphical interface of phpMyAdmin.

Disadvantage of phpMyAdmin
o phpMyAdmin is a simple interface, but quite tough for a beginner to learn.
o phpMyAdmin is difficult to install as it needs three more software tools before installation, which is-
Apache server, PHP, and MySQL.
o We have to install all these software tools individually, whereas XAMPP already contains them in a
single package. XAMPP is the easiest way to get phpMyAdmin.
o It has no schema visualization.
o phpMyAdmin is a web-based software tool which runs only on the browser, so It completely
depends on browsers.
o It does not have auto-compilation capability.

Establishing connectivity with MySQL using PHP

Introduction

To access and add content to a MySQL database, you must first establish a connection between the
database and a PHP script.

Prerequisites

 Special CREATE privileges


 A MySQL Database
 A MySQLi or PDO extension

2 Ways to Connect to MySQL database using PHP

There are two popular ways to connect to a MySQL database using PHP:

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 16

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

1. With PHP’s MySQLi Extension


2. With PHP Data Objects (PDO)

The guide also includes explanations for the credentials used in the PHP scripts and potential errors you
may come across using MySQLi and PDO.

Option 1: Connect to MySQL with MySQL Improved extension

MySQLi is an extension that only supports MySQL databases. It allows access to new functionalities found
in MySQL systems (version 4.1. and above), providing both an object-oriented and procedural interface. It
supports server-side prepared statements, but not client-side prepared statements.

The MySQLi extension is included PHP version 5 and newer.

The PHP script for connecting to a MySQL database using the MySQLi procedural approach is the
following:

<?php
$servername = "localhost";
$database = "database";
$username = "username";
$password = "password";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

echo “Connected successfully”;

mysqli_close($conn);

?>

Credentials Explained

The first part of the script is four variables (server name, database, username, and password) and their
respective values. These values should correspond to your connection details.

Next is the main PHP function mysqli_connect(). It establishes a connection with the specified database.
Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 17

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

Following is an “if statement.” It is the part of the code that shows whether the connection was established.
When the connection fails, it gives the message Connection failed. The die function prints the message and
then exits out of the script.

If the connection is successful, it displays “Connected successfully.”

When the script ends, the connection with the database also closes. If you want to end the code manually,
use the mysqli_close function.

Option 2: Connect To MySQL With PDO

PHP Data Objects (PDO) is an extension that serves as an interface for connecting to databases. Unlike
MySQLi, it can perform any database functions and is not limited to MySQL. It allows flexibility among
databases and is more general than MySQL. PDO supports both server and client-side prepared statements.

Note: PDO will not run on PHP versions older than 5.0 and is included in PHP 5.1.

The PHP code for connecting to a MySQL database through the PDO extension is:

<?php

$servername = "localhost";
$database = "database";
$username = "username";
$password = "password";
$charset = "utf8mb4";

try {

$dsn = "mysql:host=$servername;dbname=$database;charset=$charset";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo “Connection Okay”;

return $pdo

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 18

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

catch (PDOException $e)

{
echo “Connection failed: ”. $e->getMessage();
}

?>

Credentials Syntax

First, we have five variables (server name, database, username, password, and charset) and their values.
These values should correspond to your connection details.

The server name will be localhost. If connected to an online server, type in the server name of that server.

The variable charset tells the database in which encoding it will be receiving and sending data. The
recommended standard is utf8mb4.

Try and Catch Blocks

PDO’s great asset is that it has an exception class to take care of any potential problems in database queries.
It solves these problems by incorporating try and catch blocks.

If a problem arises while trying to connect, it stops running and attempts to catch and solve the
issue. Catch blocks can be set to show error messages or run an alternative code.

The first parameter in the try and catch block is DSN, which stands for data(base) source name. It is
crucial as it defines the type and name of the database, along with any other additional information.

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 19

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

In this example, we are using a MySQL database. However, PDO supports various types of databases. If
you have a different database, replace that part of the syntax (mysql) with the database you are using.

Next is the PDO variable. This variable is going to establish a connection to the database. It has three
parameters:

1. The data source name (dsn)


2. The username for your database
3. The password for your database

Following is the setAttribute method adding two parameters to the PDO:

1. PDO::ATTR_ERRMODE
2. PDO::ERRMODE_EXCEPTION

This method instructs the PDO to run an exception in case a query fails.

Add the echo “Connection Okay.” to confirm a connection is established.

Return the PDO variable to connect to the database.

After returning the PDO variable, define the PDOException in the catch block by instructing it to display a
message when the connection fails.

Potential Errors with MySQLi and PDO


Incorrect Password

The password in the PHP code needs to correspond with the one in the database. If the two do not match, a
connection with the database cannot be established. You will receive an error message saying the
connection has failed.
Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 20

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)


lOMoARcPSD|22700398

MC4023 – WEB DESIGN UNIT - 5

Possible solutions:

1. Check the database details to ensure the password is correct.


2. Ensure there is a user assigned to the database.

Unable to Connect to MySQL Server

PHP may not be able to connect to the MySQL server if the server name is not recognized. Make sure that
the server name is set to localhost.

In case of other errors, make sure to consult the error_log file to help when trying to solve any issues. The
file is located in the same folder where the script is running.

Prepared by. E.Janakiraman.MCA,Mphil., AP-MCA/APEC Page 21

Downloaded by Arun Prassath MCA (arunkrish9629@gmail.com)

You might also like