Sie sind auf Seite 1von 48

PHP AND DATABASES

Usman Rafi
What is PHP?
 PHP – an abbreviation
 Stands for “Hyper Text Pre-Processor”
 Programming Language
 Used in Web Site Development
 Used in Web Applications
 Used for Server Side Scripting
 Used to produce dynamic web pages
 Object Oriented Language
Advantages of PHP
 Light weight
 Create page dynamically
 Open source
 Object oriented
 Easy to understand
 Rich in built-in functions
Why People Prefer ASP.NET over
PHP?
 Easier development in ASP.NET
◦ Microsoft Visual Studio is an IDE that provides all
necessary facilities for developing professional web
sites using ASP.NET
◦ No proper editor is present for PHP
 Multiple scripting languages
◦ ASP.NET has two powerful scripting languages
 C# script
 VB.NET script
◦ PHP itself is a single language for scripting
Way to Install
 Way 1:
◦ Install PHP software
◦ Install MySQL software
◦ Configure both
◦ Lengthy and time consuming
◦ Requires effort to configure PHP
 Way 2:
◦ Simplest way
◦ Download XAMPP control panel
◦ Install
◦ There you go!!!!!!!!!!
XAMPP Control Panel
 Control panel provides various facilities
 Contains facilities:

◦ Apache web server (To run PHP Scripts)


◦ MySQL (Server)
◦ phpmyadmin (Utility for MySQL)
 Used to create databses
 Manage databases
 Create tables
 Manage tables
 Manage data
phpmyadmin Screenshot
General Intro
 PHP code is embedded into HTML using tags:
◦ <?php(Starting/Opening Tag)
◦ ?> (Ending/Closing Tag)
 Very similar in syntax to C++
 Statement Termination using ;

 Concatenation Operator .
 echo keyword is used to create output on page

◦ Output can be:


 Simple Text
 Variables or constants
 HTML tags (Generate Page Dynamically)
 Blank Space are allowed to increase readability
 Comments:

◦ Single line //
◦ Multiline /* */
Variables
 Temporary memory locations store data values
 Not strongly typed
 Variable can store anything
◦ Numeric values
◦ String values
◦ File names etc…………..
 Syntax:
◦ Declared using dollar sign $
 Example:
◦ $variable_name = value;
Loops and Conditional
 All those used in C++, JAVA etc
 Have same syntax as in above languages
 Conditional Structure:
◦ if structure
◦ if else structure
◦ if else if else if … ladder
◦ select case
 Looping:
◦ while loop
◦ do…while loop
◦ for loop
Create Dynamic Pages
 echo
 ‘
 Tag along with attributes and values
 ‘
 ;
 Example

◦ echo ‘<input type=“text” name=“textbox”


value=“123” />’;
Some superglobals
 $_GET[];
◦ Used to send data from one page to another using URL
◦ Data is not secure and encrypted
◦ Data can be seen in the URL
 $_POST[];
◦ Used to send data in encrypted form from one page to another
◦ Data is secure and encrypted
◦ Data cannot be seen
◦ Mostly used
 $_REQUEST[];
◦ Perform same functions as both $_POST[] and $_GET[]
 $_SESSION[];
◦ Sessions are very important
◦ Session can be same as the span in which you perform some work in email i.e. from login to
logout
◦ Used to store session information
 $_SERVER[];
◦ Another super global
◦ Contains some pre-defined variables
◦ Used to show information regarding server-name, server-ip, client-ip etc
$_SERVER[] superglobal
 $_SERVER['REMOTE_ADDR']
◦ Represents the IP address of the client
 $_SERVER['REMOTE_PORT']
◦ Represents the Port number of the client
 $_SERVER['REQUEST_URI']
◦ Directory and file name of the page requested for
 $_SERVER['SCRIPT_FILENAME']
◦ Complete path of the PHP Script file
 $_SERVER['SERVER_NAME']
◦ Displays the name of the server
◦ Usual cases it is ‘localhost’
 $_SERVER['SERVER_PORT']
◦ Displays the server port through which communication is made
 $_SERVER['SERVER_PROTOCOL']
◦ Displays the server protocol along with version number
Important Things in PHP-Database
Interaction
 HTML Forms
◦ Important Attributes
 name
 method (get or post)
 action (path of the file containing PHP script)
 HTML Form Elements
◦ Defined using <input> tag of HTML
◦ Important Attributes
 name
 type
 value
 Values given in the “name” attribute of the “input” tag of form elements
 Using $_POST[] super global
 Built-In Functions
 Connection File
 SQL Queries
si
ng
$_
PO
ST
[]
Su
pe
r
G
lo
ba
l
$_POST[]
 Super global
 An array
 Used to send data from the client side to the

server side scripts to perform some action


 Used to collect values from the form elements

that are sent using POST method


 Information sent with POST method is

◦ Secure
◦ Invisible to others
Methodology (Form File)
 Create a form
 Set name, method, action attributes
 Place form elements and name them in easy

way
 Remember names
 Place a button of submit type
Methodology (PHP Script File)
 Open PHP tag
 Place a check to find out whether submit

button was checked or not using isset


function and button name
◦ if ($_POST[‘button_name’])
 Access the data values as follows:
◦ $var1 = $_POST[‘control_name_1’];
◦ $var2 = $_POST[‘control_name_2’];
◦ echo $var1;
◦ echo $var2;
Steps
Set name, method,
Create FORM Place Controls
action Attribute

Name Controls

Start the PHP Script


File

Access Values using Place Check for the


$_POST[] Button
$_POST example STEP 1
<html>
<head>
<title>Form</title>
</head>
<body>
<form>

</form>
</body>
</html>
$_POST example STEP 2
<html>
<head>
<title>Form</title>
</head>
<body>
<form name=“sample” method=“post”
action=“handle.php” >

</form>
</body>
</html>
$_POST example STEP 3
<html>
<head>
<title>Form</title>
</head>
<body>
<form name=“sample” method=“post” action=“handle.php” >
Name:<input type=“text” />
<br/>
Age:<input type=“text” />
<br/>
<input type=“submit” />
</form>
</body>
</html>
$_POST example STEP 4
<html>
<head>
<title>Form</title>
</head>
<body>
<form name=“sample” method=“post” action=“handle.php” >
Name:<input type=“text” name=“txtname” />
<br/>
Age:<input type=“text” name=“txtage” />
<br/>
<input type=“submit” name=“btnsave” />
</form>
</body>
</html>
$_POST example STEP 5
<?php

?>
$_POST example STEP 6
<?php
if (isset($_POST[‘btnsave’]))
{

}
?>
$_POST example STEP 7
<?php
if (isset($_POST[‘btnsave’]))
{
$var_name = $_POST[‘txtname’];
$var_age = $_POST[‘’txtage];
echo “Your Name is:” . $var_name;
echo “Your Age is:” . $var_age;
}
?>
Bu
ilt
-i
n
Fu
nc
ti
on
s
Mostly Used Built-In
Functions
 mysql_connect()
 mysql_close()
 mysql_pconnect()
 mysql_error()
 mysql_select_db()
 mysql_query()
 mysql_num_rows()
 mysql_fetch_array()
mysql_connect() Function
 Used to create a connection with the mysql
database server
 Opens a connection to the database

 Connection has to be closed manually using

mysql_close() built-in function


 Requires three parameters:

◦ Server Name (Server Running the database)


◦ User Name (User Name for the database)
◦ Password (User Password for the database)
 Example
◦ mysql_connect(“server_name”,”user_name”,”password”);
mysql_close() Function
 Close an already open connection manually
with the mysql database server
 Requires only a single parameter

◦ Connection variable
 Example
◦ $conn =
mysql_connect(“server_name”,”user_name”,”passwo
rd”);
◦ mysql_close($conn);
mysql_pconnect() Function
 Used to create a connection with the mysql
database server
 Opens a connection to the database
 Connection is automatically closed and opened
after executing the query
 Requires three parameters:
◦ Server Name (Server Running the database)
◦ User Name (User Name for the database)
◦ Password (User Password for the database)
 Example
◦ mysql_pconnect(“server_name”,”user_name”,”password”);
mysql_error() Function
 Built-in function
 Displays error description if unable to create

connection to the database


mysql_select_db()
Function
 Multiple databases are present in the mysql
database server
 Used to select the database from available

mysql databases
 Requires two parameters

◦ Database Name
◦ Connection Name (Connection created)
 Example
◦ Mysql_select_db(“database_name”,connection_varia
ble);
mysql_query() Function
 Used to send SQL queries to the database for
manipulation of data
 Returns result when SELECT query is send to the
database
 Result is stored in variable
 Requires a single parameter
◦ Query in string format
 Example
◦ mysql_query(“Query Text”); (INSERT,UPDATE,DELETE
queries)
◦ $variable = mysql_query(“Query Text”); (SELECT query)
mysql_num_rows() Function
 Used when SELECT query is used
 Finds out the number of rows returned in the

result of a SQL query


 Result is zero when no row is returned from

the database
 Requires one parameter

◦ Result variable used in mysql_query() statement


 Example
◦ $result = mysql_query(“QUERY”);
◦ $rows = mysql_num_rows($result);
mysql_fecth_array() Function
 Used when SELECT query is used
 Used with while loop when more than one rows are
returned from the query
 Fetches one row at a time from the result returned in
response to a query
 Returned row is saved in a variable as an array
 Requires one parameter
◦ Result variable (Variable having query results)
 Example
◦ $result = mysql_query(“QUERY”);
◦ $rows = mysql_num_rows($result);
◦ $row = mysql_fetch_array($result);
Co
nn
ec
ti
on
Fi
le
Connection File
 Created once and used many times
 Usually named as connection.php
 Single File must be created for connection
 Code is used again and again
 Saves time and effort
 Reduces some amount of code
Connection File General
Format
 PHP Opening Tag
 Variables to store

◦ Database Server Name


◦ Database User Name
◦ Password to Access Database Server
 Connection Function to connect to database
server
◦ Error handling
 Select the Database name
 PHP Closing Tag
Connection File Example
<?php
$server_name = “localhost”;
$user_name = “root”;
$password = “”;
$database_name = “test”;
$conn = mysql_pconnect($server_name,
$user_name,$password) or die(mysql_error());
mysql_select_db($database_name);
?>

Save this as connection.php


Bu
ild
in
g
Q
ue
ri
es
in
PH
P
Important Things
 Most important are commas to be used:
◦ `` commas are used to give table names and
column names of database
◦ ‘’ commas are used to define the values or variables
to send values to database for storage
Sample Database Table
ID NAME DOB CNIC PH
1 Ali 01-01- 22222 1111
1992
2 Ahmed 02-02- 33333 2222
1993
3 Rashid 03-03- 44444 3333
1994

Table Name: test


Building INSERT Query in PHP
 All the connection procedure
 $query = “INSERT INTO `test`

VALUES(‘4’,’Umair’,’04-04-
1995’,’55555’,’4444’)”;
 mysql_query($query);

ID NAME DOB CNIC PH


1 Ali 01-01- 22222 1111
1992
2 Ahmed 02-02- 33333 2222
1993
3 Rashid 03-03- 44444 3333
1994
Building SELECT Query in
PHP
 All connection procedure
 $parameter = ‘Rashid’;
 $query = “SELECT `id`,`name` FROM `test`

WHERE `name` = ‘$parameter’;


 $result = mysql_query($query);
 $rows = mysql_num_rows($result);
 $row = mysql_fetch_array($result);
 echo $row[‘id’];
 echo $row[‘name’];

3 Rashid
Building DELETE Query in
PHP
 All connection procedure
 $parameter = ‘Rashid’;
 $query = “DELETE * FROM `test` WHERE

`name` = ‘$parameter’;
 To execute query

◦ mysql_query($query);
Building UPDATE Query in
PHP
 All connection procedure
 $oldname = ‘Rashid’;
 $newname = ‘Afzal’;
 $query = “UPDATE `test` SET `name` =

‘$newname’ WHERE `name` = ‘$oldname’;


 To execute query

◦ mysql_query($query);
PHP Flow
Set name, method,
Create FORM Place Controls
action Attribute

Name Controls

Start the PHP Script


Queries File

Access Values using Place Check for the


$_POST[] Button

Das könnte Ihnen auch gefallen