PHP function guidelines

advertisement
Vignan’s Nirula Institute of Technology & Science for Women
UNIT 6
8. PHP Programming
8.1 Introduction
PHP stands for PHP: Hypertext preprocessor
 PHP is a server side scripting language that is used to create dynamic web pages. It was
developed by by Rasmus Lerdorf in 1995. PHP originally stood for Personal Home
Page.
 The extension to the PHP files are .php,.php3, or .phtml
 The PHP processor works in two modes. If the PHP processor finds XHTML tags in the
PHP script then the code is simply copied to the output file. But when the PHP processor
finds the PHP code in the script then that code is simply interpreted and the output is
copied to the output file.

If you click for view source on the web browser you can never see the PHP script
because the output of PHP script is send directly to the browser but you can see the
XHTML tags.

PHP makes use of dynamic typing that means there is no need to declare variables in
PHP. The type of variable gets set only when it is assigned with some value.

PHP has large number of library functions which makes it flexible to develop the code in
PHP.
Installation of PHP:
There are various methods of getting PHP installed on your machine.

PHP requires Apache web server to execute its code. The Apache web server is an open
source software and can be easily downloaded from internet by using URL
Ex: http://httpd.apache.org/download.cgi

PHP can be installed on your computer from website http://www.php.net

Another approach which is the most efficient way to install Apache,PHP,MYSQL on
your computer is to use XAMP(X stands for any os) or WAMPP(W stands for windows
os). These packages support the Apache, PHP, mysql, perl.
If you install XAMP package, then the root directory can be accessed by using
http://localhost/

8.2 Creating and Running a PHP script




PHP is a server side scripting language that can be embedded in XHTML document. The
code must be enclosed with in <?php and ?>
If the PHP script is stored in some another file then if it needs to be refereed then include
construct is used. For Ex: Include(“file.inc”)
The variable names in PHP begin with $ sign.
Following are some reserved keywords that are used in PHP.
Department of IT
114
Vignan’s Nirula Institute of Technology & Science for Women
and
break
case
class
continue
default
do
else
elseif
extends
false
for
foreach
function
global
if
include
list
new
not
or
require
return
static
switch
this
true
var
virtual
while
xor
 Comments in PHP can be #, / /, /*…..*/
 PHP statements are terminated by semicolon ;
Open some suitable text editor like notepad and type the code. It is expected that the PHP code
must be stored in htdocs folder of Apache.
 If you installed the XAMPP package, then save your files in c:\xampp\htdocs with an
extension .php
 If we want to get the output of PHP code then always give the URL
http://localhost/php-examples/program-name.php
 localhost refers to c:\xampp\htdocs
Following is the example of PHP script
<html>
<head>
<title>PHP demo</title>
</head>
<body>
<?php
echo “Welcome to first PHP document”;
?>
</body>
</html>
Working with variables and constants:
8.3 Using Variables

Variables are used for storing the values.

PHP is a dynamically typed language, so it has no type declaration.

A variable starts with the $ sign, followed by the name of the variable
$vaiable_name=value;

If the value is not assigned to the variable then by default the value is NULL. The
unsigned variables are called unbound variable.
Following are some rules that must be followed while using variables.
o A variable name must begin with a letter or the underscore character
o A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
o A variable name should not contain spaces
o Variable names are case sensitive ($y and $Y are two different variables)

Department of IT
115
Vignan’s Nirula Institute of Technology & Science for Women



PHP automatically converts the variable to the correct data type, depending on its value.
Using the function IsSet the value of the variable can be tested. i.e., if IsSet($marks)
function returns TRUE that means some value is assigned to the variable marks.
If the unbounded variable gets referenced then the error reporting can be done using
error_reporting (7). The default error reporting level is 7.
PHP Variable Scopes
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has four different variable scopes:
o local
o global
o static
o parameter
Local Scope
A variable declared within a PHP function is local and can only be accessed within that function
Global Scope
A variable that is defined outside of any function, has a global scope.
Global variables can be accessed from any part of the script, EXCEPT from within a function.
To access a global variable from within a function, use the global keyword
Static Scope
When a function is completed, all of its variables are normally deleted. However, sometimes you
want a local variable to not be deleted.
To do this, use the static keyword when you first declare the variable:
Parameter Scope
A parameter is a local variable whose value is passed to the function by the calling code.
Parameters are declared in a parameter list as part of the function declaration:
Example:
<html>
<head>
<title>Using variables</title>
</head>
<body>
<?php
$x=5;
$y=3;
$z=$x+$y;
echo $z;
?>
</body>
</html>
Department of IT
116
Vignan’s Nirula Institute of Technology & Science for Women
8.4 Using Constants

Constant is an identifier that contains some value which does not change during the
execution of program.

Constant is case sensitive by default.

Generally constant identifiers are specified in upper case.

Constant name must start with letter or underscore.

Using define function we can assign value to constant. The first parameter in define
function is name of constant and second parameter is the value which is to be assigned.
Ex: define(“myvalue”,”10”);
 It is valid.
Define(“1myvalue”,”something”);
It is not valid.
8.5 Data types
A data type is a classification identifying one of various types of data, such as realvalued, integer or Boolean, that determines the possible values for that type.
There are 4 scalar data types used in PHP.
8.5.1 Integer type
For displaying integer value the Integer type is used. It is similar to long type in C. The
size is 32 bit.
8.5.2 Double type
For displaying real values the double data type is used. It includes numbers with decimal
point, exponentiation or both. The exponent can be represented by E or e followed by integer
literal. Ex: 1.2*E2
8.5.3 String type
There is no character data type in PHP. If the character to be represented then it is
represented using the same type itself; but in this case the string is considered to be of length 1.
The string literals can be defined using either single or double quotes. In single quotes the
escape sequence or the values of literals can not be recognized by PHP but in double quotes the
escape sequence can be recognized.
Ex: “The total marks=$marks” Display value of marks variable.
‘The total marks=$marks’ Display as it is.
8.5.4 Boolean type
Two types of values can be identified by Boolean type and those are TRUE and FALSE.
If Boolean values are used in context of integer type variable then TRUE will be interpreted as 1
and FALSE will be interpreted as 0. If Boolean values are used in context of double type variable
then FALSE will be interpreted as 0.0.
Department of IT
117
Vignan’s Nirula Institute of Technology & Science for Women
8.6 Operators
Operators are the symbol which operates on value or a variable. PHP supports different
types of operators.
8.6.1 Arithmetic Operators:
Arithmetic Operators are used to perform different types of arithmetic operations like
addition, subtraction, multiplication, division, modulo division etc.. While using arithmetic
operators if both operators are integer then result will be integer itself. If both operators are
double then result will be double.
PHP has large number of predefined functions which are listed below.
Function
Purpose
floor
The largest integer less than or equal to the parameter is returned.
Ex: floor(4.9 ) returns 4.
ceil
The smallest integer greater than or equal to the parameter is returned.
Ex:ceil(4.9) returns 5.
round
Nearest integer is returned.
abs
Returns absolute value of parameter
min
It returns smallest element
max
It returns larger element
8.6.2 Relational Operators:
 The relational operators used in PHP are <,>,<=,>=,==,!=

The operator === is used in PHP. If both operands are equal and are of the same type,
this operator returns true; otherwise, it returns false.

The operator !== is used in PHP. If both operands are not equal, or they are not of the
same type, this operator returns true; otherwise, it returns false.
 If one of operand in the six operators is not same then the coercion will occur
automatically.
8.6.3 Logical Operators: Logical operators are used to combine two or more logical
expressions. Logical operators treat their operands as Boolean values and return a Boolean value.
The logical operators are:
and (&&)  The result of the logical AND operation is true if and only if both operands are true;
otherwise, it is false.
or(| |)  The result of the logical OR operation is true if either operand is true; otherwise, the
result is false.
Xor  The result of the logical XOR operation is true if either operand, but not both, is true;
otherwise, it is false.
Department of IT
118
Vignan’s Nirula Institute of Technology & Science for Women
String operations:
The string concatenation operator (.) appends the right hand operand to the left-hand
operand and returns the resulting string. Operands are first converted to strings, if necessary.
Ex: $n = 5;
$s = 'There were ' . $n . ' ducks.';
// $s is 'There were 5 ducks'
Various functions used for string handling are as follows.
strlen(string1) It finds total number of characters in string.
Strcmp(string1,string2)It compares two strings for equality. If those two are equal it returns 0.
Strtolower(string1) It converts characters in string1 to lowercase.
Strtoupper(string1) It converts characters in string1 to uppercase.
trim(string1) It eliminates white space from both ends of string.
Type conversion:
PHP supports both Implicit & Explicit type conversions.
a) Implicit type conversion (coercion):
One data type will be automatically converted to other data type. i.e., higher data type
will be converted to lower data type. The coercion takes place between numeric and string types.
When double value is converted to integer the fractional part will be eliminated and the
value is not rounded.
b) Explicit type conversion (Casting):
Casting is used to convert one data type into another data type explicitly.
Syntax: (datatype) $variable_name
Ex: (int)$marks
Syntax: Conversion_function($variable_name)
Ex: Intval($marks)
Syntax: settype($variable_name,”datatype”)
Ex: settype($marks,”integer”);
The function gettype is useful to obtain data type of variable.
Output:
PHP is a server side scripting language that can be embedded in XHTML document. i.e.,
we can use XHTML tags in PHP while displaying output.
The print function is used to create simple unformatted output.
Ex: print “I am proud of my <b> Country</b>”
The numeric value can also be displayed using print.  print(200); will display output as 200.
PHP also make use of printf function used in C.
Ex: printf(“The student %d has %f marks”,$rollno,$marks);
Department of IT
119
Vignan’s Nirula Institute of Technology & Science for Women
UNIT 7
9. Controlling Program Flow
9.1 Conditional statements
The conditional statements in PHP are similar to the conditional statements that are used
in C. Conditional statements, such as if/else and switch, allow a program to execute different
pieces of code, or none at all, depending on some condition.
 if: The if statement checks the truthfulness of an expression and, if the expression is true,
evaluates a statement. An if statement looks like:
if (expression)
statement
To specify an alternative statement to execute when the expression is false, use the else keyword:
if (expression)
statement-1;
else
statement-2;
Ex:
<html>
<head>
<title>PHP demo</title>
</head>
<body>
<?php
echo “selection statements”;
$a=10;
$b=20;
$c=30;
if($a>$b)
if($a>$c)
echo “<b>a is largest number</b>”;
else
echo “<b>c is largest number</b>”;
else
if($b>$c)
echo “<b>b is largest number</b>”;
else
echo “<b>c is largest number</b>”;
?>
</body>
</html>
Department of IT
120
Vignan’s Nirula Institute of Technology & Science for Women
 Switch: A switch statement is given an expression and compares its value to all cases in
the switch; all statements in a matching case are executed, up to the first break keyword it
finds. If none match, and a default is given, all statements following the default keyword are
executed, up to the first break keyword encountered.
Ex:
<html>
<head>
<title>PHP demo</title>
</head>
<body>
<?php
$today=getdate();
switch($today[‘weekday’])
{
case “Monday”: print:”Today is Monday”;
break;
case “Tuesday”: print:”Today is Tuesday”;
break;
case “Wednesday”: print:”Today is Wednesday”;
break;
case “Thursday”: print:”Today is Thursday”;
break;
case “Friday”: print:”Today is Friday”;
break;
case “Saturday”: print:”Today is Saturday”;
break;
case “Sunday”: print:”Today is Sunday”;
break;
default: print” Invalid choice”;
}
?>
</body>
</html>
9.2 Control statements
Loops, such as while, do-while and for, support the repeated execution of particular
segments of code.
 while: It takes the following form:
while (expression)
statements;
If the expression evaluates to true, the statement is executed and then the expression is reevaluated
Department of IT
121
Vignan’s Nirula Institute of Technology & Science for Women
Ex:
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br>";
$i++;
}
?>
</body>
</html>
The
The
The
The
The
number
number
number
number
number
is
is
is
is
is
1
2
3
4
5
 do-while: The do...while statement will always execute the block of code once, it will
then check the condition, and repeat the loop while the condition is true.
It takes the following form:
do
{
code to be executed;
The number is 2
}
The number is 3
while (condition);
The number is 4
Ex:
The number is 5
<html>
The number is 6
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i<=5);
?>
</body>
</html>
 for loop: It takes the following form:
for (init; condition; increment)
{
code to be executed;
}
Parameters:
Department of IT
122
Vignan’s Nirula Institute of Technology & Science for Women
o init: Mostly used to set a counter
o condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues.
If it evaluates to FALSE, the loop ends.
o increment: Mostly used to increment a counter
Ex:
<html>
<body>
The number is 1
<?php
The number is 2
for ($i=1; $i<=5; $i++)
The number is 3
{
The number is 4
The number is 5
echo "The number is " . $i . "<br>";
}
?>
</body>
</html>
 foreach loop: The foreach statement allows you to iterate over elements in an array. The
following is general syntax for foreach loop.
foreach ($array as $value)
{
code to be executed;
}
one
Ex:
two
three
<html>
<body>
<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br>";
}
?>
</body>
</html>
Department of IT
123
Vignan’s Nirula Institute of Technology & Science for Women
9.3 Arrays

Array is a collection of similar type of elements. But in PHP you can have the elements
of mixed type together in a single array.
 In each PHP, each element has two parts key and value.
 In PHP there are two types of arrays.
o Indexed: Arrays with numeric index
o Associative: Arrays with named index
 The key represents the index at which the value of element can be stored.
9.3.1 Array creation
There are two ways to create the array in PHP.

Use the function array to create the array.
$mylist=array(10,20,30,40,50);

Assign the value directly to the array element.
$mylist[0]=0;
 An empty array can be created by using array construct.
$mylist=array();
9.3.2 Accessing array elements
Using an array subscript we can access the array element. The value of subscript is
enclosed with in square brackets.
$citycode[0]=”522006”;
$name[0]=”Vignan”;
Multiple values can be set to a single scalar variable using array.
$people=array(“Meena”,”Teena”,”Heena”);
list($operator,$accountant,$manager)=$people;
By the above assignment Meena becomes operator, Teena becomes accountant and Heena
becomes manager.
9.3.3 Functions for dealing with arrays
 The unset function is used to remove particular element from the array.
Ex:
<?php
$mylist=array(10,20,30,40,50);
unset($mylist[1]);
for($i=0;$i<=4;$i++)
{
print $mylist[i];
print “ “;
}
?>
Department of IT
124
Vignan’s Nirula Institute of Technology & Science for Women

The array_keys and array_values functions are used to return the array keys and the
values at corresponding key.
Ex:
<?php
$mylist=array(10=>”AAA”,20=>”BBB”,30=>”CCC”,40=>”DDD”,50=>”EEE”);
$Roll=array_keys($mylist);
print_r($Roll);
print “<br/>”;
print_r($Name);
?>

The existence of a particular key can be checked by using array_key_exists function.
This function returns the Boolean value.
 The is_array returns the Boolean value. This function takes a variable as a parameter. If
the function returns TRUE it means the parameter is passed to this function is of array
type.
 The implode and explode functions are used to break the word into strings or vice versa.
9.3.4 Sequential access to array elements
 The array element reference start at the first element and every array maintains an
internal pointer using which the next element can be easily accessible.
 It helps to access the array elements in sequential manner.
 The pointer current is used to point to the current element in the array. Using next
function the next subsequent element can be accessed.
Ex: current
<?php
peter
$people = array("Peter", "Joe", "Glenn", "Cleveland");
echo current($people) . "<br>";
?>
Ex: next
Peter
<?php
Joe
$people = array("Peter", "Joe", "Glenn", "Cleveland");
echo current($people) . "<br>";
echo next($people);
?>

Using each function we can iterate through array elements.
<?php
Array ( [1] => Peter [value] => Peter [0]
$people = array("Peter", "Joe", "Glenn", "Cleveland"); => 0 [key] => 0 )
print_r (each($people));?>

The foreach function is used to iterate through all the elements of loop.
Department of IT
125
Vignan’s Nirula Institute of Technology & Science for Women
9.3.5 Sorting arrays
 Sorting is a process in which the elements of arrays in some specific order. There are two
types of ordering such as Ascending order and Descending order.
 PHP used the following functions to sort the arrays.
o sort() - sort arrays in ascending order
Ex:
2
<?php
$numbers=array(4,6,2,22,11);
4
sort($numbers);
6
$arrlength=count($numbers);
11
for($x=0;$x<$arrlength;$x++)
{
22
echo $numbers[$x];
echo "<br>";
}
?>
o rsort() - sort arrays in descending order
Volvo
Ex:
<?php
Toyota
$cars=array("Volvo","BMW","Toyota");
BMW
rsort($cars);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
o asort() - sort associative arrays in ascending order, according to the value
Ex:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Department of IT
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
126
Vignan’s Nirula Institute of Technology & Science for Women
o ksort() - sort associative arrays in ascending order, according to the key
Ex:
<?php
Key=Ben, Value=37
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
Key=Joe, Value=43
Key=Peter, Value=35
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
o arsort() - sort associative arrays in descending order, according to the value
Ex:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
Key=Joe, Value=43
arsort($age);
Key=Ben, Value=37
foreach($age as $x=>$x_value)
{
Key=Peter, Value=35
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
o krsort() - sort associative arrays in descending order, according to the key
Ex:
<?php
Key=Peter, Value=35
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
Key=Joe, Value=43
krsort($age);
foreach($age as $x=>$x_value)
Key=Ben, Value=37
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
9.4 Functions
A function will be executed by a call to the function.You may call a function from
anywhere within a page.
9.4.1 Create a PHP Function
A function will be executed by a call to the function.
Syntax
function functionName(parameter list)
{
code to be executed;
}
Department of IT
127
Vignan’s Nirula Institute of Technology & Science for Women
PHP function guidelines:
 Give the function a name that reflects what the function does
 The function name can start with a letter or underscore (not a number)
 return statement is used to return some values from functions body.
Example:
<?php
function myphp()
{
print”<i>This is functions</i>”;
}
print”The functions program”;
print”</br>”;
myphp();
?>
9.4.2 Parameters:
 The parameters that are passed to the function during function call are called actual
parameters.
 The parameters that are passed to the function during function definition are called
formal parameters. It is not necessary that the number of actual parameters should match
with the number of formal parameters.


If there are less actual parameters and more formal parameters then value of formal
parameter is some unbounded one.
If there are more actual parameters and less formal parameters then excess of actual
parameter ignored.
 The default parameter passing technique in PHP is pass by value.
Example:
<?php
function add($a,$b)
{
$c=$a+$b;
}
print”The addition of two numbers:”;
print:</br>”;
$x=10;
$y=20;
add(x,y);
?>
Department of IT
128
Vignan’s Nirula Institute of Technology & Science for Women
9.4.3 Scope of a variable:
In PHP the scope of a variable is local. i,e., we can define a variable within a function and
by the same another variable can be defined outside the function.
Ex:
<?php
function one()
{
The value of a=10
$a=10;
The value of a=20
print”The value of a=$a”;
}
myfun();
print”</br>”;
$a=20;
print”The value of a=$a”;
?>
We can also define a global variable by using the keyword global.
<?php
function one()
{
global $a;
$a=10;
print”The value of a=$a”;
The value of a=10
The value of a=5
}
myfun();
print”</br>”;
$a=$a-5;
print”The value of a=$a”;
?>
9.4.4 The lifetime of a Variable
 The lifetime of a variable can be defined as the time from which it is used first to the end
of function execution.

In PHP the static variable is used to remember previous values.

The lifetime of static variable is the time when the variable if first used and it ends when
the script terminates its execution.
Ex:
static $count=0;
Department of IT
129
Vignan’s Nirula Institute of Technology & Science for Women
9.5 Working with forms
 PHP is used for form handling. For that purpose the simple form can be designed
in XHTML and the value of the fields defined on the form can be transmitted to
the PHP script using GET and POST methods.
 For Forms that are submitted via “GET” method, we can obtain the form via the
$_GET array variable.
 For Forms that are submitted via “POST” method, we can obtain the form via the
$_POST array variable.
The most important thing to notice when dealing with HTML forms and PHP is that any form
element in an HTML page will automatically be available to your PHP scripts.
Ex:
The example below contains an HTML form with two input fields and a submit button:
“Form.php”
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
When a user fills out the form above and clicks on the submit button, the form data is sent to a
PHP file, called "welcome.php":
"welcome.php"
Welcome Vignan Nirula!
<html>
You are 6 years old.
<body>
Welcome <?php echo $_POST["fname"]; ?>!<br>
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
User input should be validated on the browser whenever possible. Browser validation is
faster and reduces the server load.
Department of IT
130
Vignan’s Nirula Institute of Technology & Science for Women
9.6 Database using MYSQL
MYSQL is a kind of database in which the records are stored in entities called ‘tables’. In
the tables the data is arranged in the rows and columns. Query is a request for retrieving
information from the database. We can query a database to retrieve particular information.
9.6.1 Using Queries
a) Creating database
mysql>CREATE DATABASE mydb;
Query Ok, 1 row affected (0.15 sec)
b) Displaying all the databases
mysql>SHOW DATABASES;
database
mydb
mysql
students
test
4 rows in set (0.06 sec)
c) Selecting particular database:
mysql>USE MYDB;
Database changed
d) Creating tables
We must create a table inside a database, so it is common to use create table command
after USE database command. While creating table we must specify the table fields.
mysql>CREATE TABLE mytable(id INT(4),name VARCHAR(20));
e) Displaying tables in database
After creating the tables using SHOW command we can see all the existing tables in the
current database.
mysql>SHOW TABLES;
tables_in_mydb
mytable
f) Displaying the table fields
For knowing different fields of table use DESCRIBE command.
mysql>DESCRIBE mytable;
Field
Type
Null
Key
Default
id
int(4)
YES
NULL
name
varchar(20)
YES
NULL
Department of IT
extra
131
Vignan’s Nirula Institute of Technology & Science for Women
g) Inserting values into the table
We can insert only one complete record at a time.
mysql>INSERT INTO mytable VALUES(1,’Vignan’);
h) Displaying the contents of table
To display contents of table use SELECT command.
mysql>SELECT * FROM mytable;
id
name
1
vignan
1 row in set (0.05 sec)
We can also write SELECT statement for selecting particular row by specifying some condition
such as
mysql>SELECT * FROM mytable where id=1;
or
mysql>SELECT * FROM mytable where name=’Vignan’;
We can insert the rows into table by using INSERT command repeatedly.
If we want to get records in sorted manner then we use ORDERBY clause.
mysql>SELECT * FROM mytable;
id
name
1
Vignan
Nirula
2
3
IT A
4
IT B
4 rows in set (0.00 sec)
mysql>SELECT * FROM mytable ORDERBY name;
id
name
IT A
1
2
IT B
3
Nirula
4
Vignan
4 rows in set (0.00 sec)
i) Updating the record
UPDATE command can used to update the record in a table.
mysql>UPDATE mytable -> SET name=’CSE’ -> WHERE id=4;
Department of IT
132
Vignan’s Nirula Institute of Technology & Science for Women
j) Deleting the record
Use DELETE command for deleting a particular record from table.
mysql>DELETE FROM mytable
-> where id=3;
Then use SELECT command to display the contents of table.
k) Deleting the table
The table can be deleted by using the command DROP.
mysql>drop table mytable;
9.7 PHP and MYSQL Connectivity
9.7.1 Connection to Server
Before we can access data in a database, we must open a connection to the MySQL
server. To establish a connection between PHP and MYSQL use the function mysql_connect().
The syntax of mysql_connect() is as follows.
mysql_connect(host,username,password,dbname);
Ex:
<?php
// Create connection
$con=mysql_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysql_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
else
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
mysqli_close($con);
?>
9.7.2 Creating database
The CREATE DATABASE statement is used to create a database table in MySQL. We
must add the CREATE DATABASE statement to the mysqli_query() function to execute the
command.
Department of IT
133
Vignan’s Nirula Institute of Technology & Science for Women
EX:
<?php
$con=mysql_connect("example.com","peter","abc123");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
// Create database
$sql="CREATE DATABASE my_db";
if (mysql_query($con,$sql))
{
echo "Database my_db created successfully";
}
else
{
echo "Error creating database: " . mysql_error($con);
}
?>
9.7.3 Selecting database
The SELECT statement is used to select data from a database.
Syntax
SELECT column_name(s) FROM table_name
Ex:
<?php
$con=mysql_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$result = mysql_query($con,"SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
} mysql_close($con); ?>
Department of IT
134
Vignan’s Nirula Institute of Technology & Science for Women
9.7.4 Listing the database
There are various databases present in the MYSQL which can be displayed using the
function mysql_list_db().
Ex:
<?php
$con=mysql_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$db_lists=my_list_db($con)
While($i=$mysql_fetch_object($db_list))
{
echo $i->Database. “\n”
//present database will be displayed
}
mysql_close($con);
?>
9.7.5 Listing table names
The tables present inside the databases. The function mysql_list_tables function is used
to display the tables present in the database or we can use mysql_query
Ex:
<?php
$con=mysql_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
if(!$table_list)
{
echo “Error” . mysql_error();
}
While($i=$mysql_fetch_row($table_list))
{
echo $i[0]. “\n”;
} mysql_close($con); ?>
Department of IT
135
Vignan’s Nirula Institute of Technology & Science for Women
9.7.6 Creating a table
The CREATE TABLE statement is used to create a table in MySQL. We must add the
CREATE TABLE statement to the mysqli_query() function to execute the command.
Ex:
<?php
$con=mysql_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
// Create table
$sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";
// Execute query
if (mysql_query($con,$sql))
{
echo "Table persons created successfully";
}
else
{
echo "Error creating table: " . mysql_error($con);
}
mysql_close($con);
?>
9.7.7 Inserting data
The INSERT INTO statement is used to add new records to a database table.
Ex:
<?php
$con=mysql_connect("example.com","peter","abc123","my_db");
if (($con)
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
mysql_select_db(“my_db”,$con);
$query=”INSERT INTO my_table(id,name) VALUES(1,’SHILPA’);
mysql_query($query,$con);
$query=” INSERT INTO my_table(id,name) VALUES(2,’MONIKA’);
Department of IT
136
Vignan’s Nirula Institute of Technology & Science for Women
mysql_query($query,$con);
mysql_close($con);
?>
9.7.8 Altering Table
The ALTER table command is useful for various reasons such as to add some columns in
the existing table, to delete some column from the table, for changing the size of some field or to
change the name of column.
Ex:
$con=mysql_connect("example.com","peter","abc123","my_db");
if (($con)
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
mysql_select_db(“my_db”,$con);
$query=” ALTER TABLE my_table ADD COLUMN addr VARCHAR(30)”;
mysql_query($query,$con);
mysql_close($con);
?>
9.7.9 Deleting Database
The DELETE FROM statement is used to delete records from a database table.
Syntax
DELETE FROM table_name WHERE some_column = some_value
Ex:
<?php
$con=mysql_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
mysql_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");
mysql_close($con);
?>
Department of IT
137
Vignan’s Nirula Institute of Technology & Science for Women
Similarly we can delete a database using the query DROP.
Ex:
<?php
$con=mysql_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
mysql_select_db(“mydb”,$con);
$query=” DROP DATABASE mydb”;
mysql_query($query,$con);
mysql_close($con);
?>
Department of IT
138
Download