PHP Mysql
PHP Mysql
PHP Mysql
INTRODUCTION TO PHP
What is PHP
PHP is an open-source, interpreted, and object-oriented scripting language that
can be executed at the server-side. PHP is well suited for web development.
Therefore, it is used to develop web applications (an application that executes
on the server and generates the dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in
1995. Some important points need to be noticed about PHP are as followed:
PHP stands for Hypertext Preprocessor.
PHP is an interpreted language, i.e., there is no need for compilation.
PHP is faster than other scripting languages, for example, ASP and JSP.
PHP is a server-side scripting language, which is used to manage the
dynamic content of the website.
PHP can be embedded into HTML.
PHP is an object-oriented language.
PHP is an open-source scripting language.
PHP is simple and easy to learn language.
History
PHP was developed by Rasmus Lerdorf in 1994 as a simple set of CGI
binaries written in C. He called this suite of scripts "Personal Home Page
Tools". It can be regarded as PHP version 1.0.
In April 1996, Rasmus introduced PHP/FI. Included built-in support for
DBM, mSQL, and Postgres95 databases, cookies, user-defined function
support. PHP/FI was given the version 2.0 status.
PHP: Hypertext Preprocessor – PHP 3.0 version came about when Zeev
Suraski and Andi Gutmans rewrote the PHP parser and acquired the
present-day acronym. It provided a mature interface for multiple
databases, protocols and APIs, object-oriented programming support, and
consistent language syntax.
PHP 4.0 was released in May 2000 powered by Zend Engine. It had
support for many web servers, HTTP sessions, output buffering, secure
ways of handling user input and several new language constructs.
PHP 5.0 was released in July 2004. It is mainly driven by its core, the
Zend Engine 2.0 with a new object model and dozens of other new
Innahai Anugraham 1
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 2
BCA VI SEM PHP &MySQL Rajadhani Degree college
Performance:
PHP script is executed much faster than those scripts which are written in
other languages such as JSP and ASP. PHP uses its own memory, so the
server workload and loading time is automatically reduced, which results in
faster processing speed and better performance.
Open Source:PHP source code and software are freely available on the web.
You can develop all the versions of PHP according to your requirement
without paying any cost. All its components are free to download and use.
Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding
with it.
Innahai Anugraham 3
BCA VI SEM PHP &MySQL Rajadhani Degree college
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system.
A PHP application developed in one OS can be easily executed in other OS
also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or
warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be
taken automatically at the time of execution based on the type of data it
contains on its value.
Web servers Support:
PHP is compatible with almost all local servers used today like Apache,
Netscape, Microsoft IIS, etc.
Security:
PHP is a secure language to develop the website. It consists of multiple
layers of security to prevent threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP
can do the same work in a few lines of code. It has maximum control over
the websites like you can make changes easily whenever you want.
A Helpful PHP Community:
It has a large community of developers who regularly updates
documentation, tutorials, online help, and FAQs. Learning PHP from the
communities is one of the significant benefits.
Innahai Anugraham 4
BCA VI SEM PHP &MySQL Rajadhani Degree college
Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP)
software stack. It is available for all operating systems. There are many AMP
options available in the market that are given below:
Innahai Anugraham 5
BCA VI SEM PHP &MySQL Rajadhani Degree college
<html>
<body>
<?php
echo "<h2>Hello First PHP</h2>";
?>
</body>
</html>
Output:
Hello First PHP
How to run PHP programs in XAMPP
How to run PHP programs in XAMPP PHP is a popular backend
programming language. PHP programs can be written on any editor, such as
- Notepad, Notepad++, Dreamweaver, etc. These programs save with .php
extension, i.e., filename.php inside the htdocs folder.
For example - p1.php.
As I'm using window, and my XAMPP server is installed in D drive. So, the
path for the htdocs directory will be "D:\xampp\htdocs".
PHP program runs on a web browser such as - Chrome, Internet Explorer,
Firefox, etc. Below some steps are given to run the PHP programs.
Step 1: Create a simple PHP program like hello world.
<?php
echo "Hello World!";
?>
Step 2: Save the file with hello.php name in the htdocs folder, which resides
inside the xampp folder.
Note: PHP program must be saved in the htdocs folder, which resides inside
the xampp folder, where you installed the XAMPP. Otherwise it will
generate an error - Object not found.
Step 3: Run the XAMPP server and start the Apache and MySQL.
Innahai Anugraham 6
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 7
BCA VI SEM PHP &MySQL Rajadhani Degree college
<?php
echo "Hello by PHP echo
this is multi line
text printed by
PHP echo statement
";
?>
Output:
Hello by PHP echo this is multi line text printed by PHP echo statement
PHP echo: printing escaping characters
<?php
echo "Hello escape \"sequence\" characters";
?>
Output:
Hello escape "sequence" characters
PHP echo: printing variable value
<?php
$msg="Hello JavaTpoint PHP";
echo "Message is: $msg";
?>
Output:
Message is: Hello JavaTpoint PHP
PHP print
PHP print statement can be used to print the string, multi-line strings,
escaping characters, variable, array, etc. Some important points that you
must know about the echo statement are:
Innahai Anugraham 8
BCA VI SEM PHP &MySQL Rajadhani Degree college
eg.,
<?php
print "Hello by PHP print
this is multi line
text printed by
PHP print statement
";
?>
Output:Hello by PHP print this is multi line text printed by PHP print statement
Difference between echo and print
echo
echo is a statement, which is used to display the output.
echo can be used with or without parentheses.
echo does not return any value.
We can pass multiple strings separated by comma (,) in echo.
echo is faster than print statement.
print
print is also a statement, used as an alternative to echo at many times to
display the output.
print can be used with or without parentheses.
print always returns an integer value, which is 1.
Using print, we cannot pass multiple arguments.
print is slower than echo statement.
PHP Comments
PHP Single Line Comments
There are two ways to use single line comments in PHP.
// (C++ style single line comment)
# (Unix Shell style single line comment)
<?php
// this is C++ style single line comment
# this is Unix Shell style single line comment
Innahai Anugraham 9
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 10
BCA VI SEM PHP &MySQL Rajadhani Degree college
object
PHP Data Types: Special Types
There are 2 special data types in PHP.
resource
NULL
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values:
TRUE (1) or FALSE (0).
Example:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
PHP Integer
It holds only whole numbers, i.e., numbers without fractional part or decimal
points.
Rules for integer:
An integer can be either positive or negative.
An integer must not contain decimal point.
Integer can be decimal (base 10), octal (base 8), or hexadecimal (base
16).
The range of an integer must be lie between 2,147,483,648 and
2,147,483,647 i.e., -2^31 to 2^31.
Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
Innahai Anugraham 11
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 12
BCA VI SEM PHP &MySQL Rajadhani Degree college
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=>
string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
PHP object
Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared.
Example:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:
Bike Model: Royal Enfield
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store
some function calls or references to external PHP resources. For example - a
database call. It is an external resource.
PHP Null
Innahai Anugraham 13
BCA VI SEM PHP &MySQL Rajadhani Degree college
Null is a special data type that has only one value: NULL. There is a convention
of writing it in capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
PHP Variables
In PHP, a variable is declared using a $ sign followed by the variable name.
Here, some important points to know about variables:
As PHP is a loosely typed language, so we do not need to declare the data types
of the variables. It automatically analyzes the values and makes conversions to
its correct datatype.
After declaring a variable, it can be reused throughout the code.
Assignment Operator (=) is used to assign the value to a variable.
Syntax of declaring a variable in PHP is given below:
$variablename=value;
PHP Variable Scope
The scope of a variable is defined as its range in the program under which it can
be accessed.
PHP has three types of variable scopes:
Local variable: The variables that are declared within a function are called
local variables for that function.
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
Innahai Anugraham 14
BCA VI SEM PHP &MySQL Rajadhani Degree college
?>
Global variable: The global variables are the variables that are declared outside
the function.
<?php
$name = "Sanaya Sharma"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Note: Without using the global keyword, if you try to access a global variable
inside the function, it will generate an error that the variable is undefined.
Static variable: It is a feature of PHP to delete the variable, once it completes
its execution and memory is freed. We use the static keyword before the variable
to define a variable, and this variable is called as static variable.
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable
$num1++;
//increment in static variable
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}
//first function call
static_var();
Innahai Anugraham 15
BCA VI SEM PHP &MySQL Rajadhani Degree college
?>
Output:
Static: 4
Non-static: 7
Static: 5
Non-static: 7
PHP Constants
PHP constants are name or identifier that can't be changed during the execution
of the script except for magic constants, which are not really constants. Unlike
variables, constants are automatically global throughout the script. PHP
constants can be defined by 2 ways:
Using define() function:Use the define() function to create a constant. It
defines constant at run time.
Syntax:
define(name, value, case-insensitive)
name: It specifies the constant name.
value: It specifies the constant value.
case-insensitive: Specifies whether a constant is case-insensitive. Default
value is false. It means it is case sensitive by default.
Eg.,
<?php
define("MESSAGE","Hello JavaTpoint PHP");
echo MESSAGE;
?>
Using const keyword: The const keyword defines constants at compile
time. It is a language construct, not a function. The constant defined using
const keyword are case-sensitive.
<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
Constant() function
Innahai Anugraham 16
BCA VI SEM PHP &MySQL Rajadhani Degree college
There is another way to print the value of constants using constant() function
instead of using the echo statement.
Syntax
constant (name)
<?php
define("MSG", "JavaTpoint");
echo MSG, "</br>";
echo constant("MSG");
//both are similar
?>
Magic Constants
Magic constants are the predefined constants in PHP which get changed on the
basis of their use. They start with double underscore (__) and ends with double
underscore.
There are nine magic constants in PHP. In which eight magic constants start and
end with double underscores (__).
1. __LINE__:It returns the current line number of the file, where this
constant is used.
2. __FILE__:This magic constant returns the full path of the executed file,
where the file is stored.
3. __DIR__:It returns the full directory path of the executed file.
4. __FUNCTION__:This magic constant returns the function name, where
this constant is used.
5. __CLASS__:It returns the class name, where this magic constant is used.
6. __TRAIT__:This magic constant returns the trait name, where it is used.
7. __METHOD__:It returns the name of the class method where this magic
constant is included.
8. __NAMESPACE__:It returns the current namespace where it is used.
9. ClassName::class: This magic constant does not start and end with the
double underscore (__). It returns the fully qualified name of the
ClassName. ClassName::class is added in PHP 5.5.0. It is useful with
namespaced classes.
All of the constants are resolved at compile-time instead of run time, unlike the
regular constant. Magic constants are case-insensitive.
Innahai Anugraham 17
BCA VI SEM PHP &MySQL Rajadhani Degree college
PHP Operators
Arithmetic Operators
Innahai Anugraham 18
BCA VI SEM PHP &MySQL Rajadhani Degree college
Bitwise Operators
& And $a & $b Bits that are 1 in both $a and $b are set
to 1, otherwise 0.
~ Not ~$a Bits that are 1 set to 0 and bits that are
0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
=== Identical $a===$b Return TRUE if $a is equal to $b, and they are of
same data type
!== Not identical $a!== $b Return TRUE if $a is not equal to $b, and they are
not of same data type
Innahai Anugraham 19
BCA VI SEM PHP &MySQL Rajadhani Degree college
<= Less than or equal $a <= $b Return TRUE if $a is less than or equal $b
to
Logical Operators
Operator Name Example Explanation
Innahai Anugraham 20
BCA VI SEM PHP &MySQL Rajadhani Degree college
String Operators
Array Operators
Type Operators
The type operator instanceof is used to determine whether an object, its parent
and its derived class are the same type or not.
Eg.,
$charu = new Developer();
//testing the type of object
if( $charu instanceof Developer)
Innahai Anugraham 21
BCA VI SEM PHP &MySQL Rajadhani Degree college
{
echo "Charu is a developer.";
}
else
{
echo "Charu is a programmer.";
}
Execution Operators
PHP has an execution operator backticks (``). PHP executes the content of
backticks as a shell command. Execution operator and shell_exec() give the
same result
Eg,
echo `dir`
Error Control Operators
PHP has one error control operator, i.e., at (@) symbol. Whenever it is used
with an expression, any error message will be ignored that might be generated
by that expression.
Eg.,
@file ('non_existent_file')
PHP $ and $$ Variables
The $var (single dollar) is a normal variable with the name var that stores any
value like string, integer, float, etc.
The $$var (double dollar) is a reference variable that stores the value of the
$variable inside it.
Eg.,
<?php
$x = "abc";
$$x = 200;
echo $x."<br/>";
echo $$x."<br/>";
echo $abc;
?>
o/p:
Innahai Anugraham 22
BCA VI SEM PHP &MySQL Rajadhani Degree college
UNIT II
Programming with PHP
PHP If Else
PHP if else statement is used to test condition. There are various ways to use if
statement in PHP.
If
If statement is used to executes the block of code exist inside the if
statement only if the specified condition is true.
Syntax
if(condition){
//code to be executed
}
Eg.,
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
if-else
If-else statement executes one block of code if the specified condition is
true and another block of code if the condition is false.
Syntax:
if(condition){
//code to be executed if true
}else{
//code to be executed if false
}
Eg.,
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
} ?>
Innahai Anugraham 23
BCA VI SEM PHP &MySQL Rajadhani Degree college
if-else-if
if-else-if is a special statement used to combine multiple if?.else
statements. So, we can check multiple conditions using this statement.
Syntax:
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}
Eg,
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input"; } ?>
Innahai Anugraham 24
BCA VI SEM PHP &MySQL Rajadhani Degree college
nested if
The nested if statement contains the if block inside another if block. The
inner if statement executes only when specified condition in outer if
statement is true.
Syntax:
if (condition) {
//code to be executed if condition is true
if (condition) {
//code to be executed if condition is true
}
}
Eg.,
<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>
PHP Switch
PHP switch statement is used to execute one statement from multiple
conditions. It works like PHP if-else-if statement.
Syntax
switch(expression){
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
Innahai Anugraham 25
BCA VI SEM PHP &MySQL Rajadhani Degree college
......
default:
code to be executed if all cases are not matched;
}
Example:
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
PHP For Loop
PHP for loop can be used to traverse set of code for the specified number of
times.
Syntax:
for(initialization; condition; increment/decrement){
//code to be executed
}
Eg.,
<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>
PHP Nested For Loop
We can use for loop inside for loop in PHP, it is known as nested for loop. The
inner for loop executes only when the outer for loop condition is found true.\
Innahai Anugraham 26
BCA VI SEM PHP &MySQL Rajadhani Degree college
Eg.,
<?php
for($i=1;$i<=3;$i++){
for($j=1;$j<=3;$j++){
echo "$i $j<br/>";
}
}
?>
PHP For Each Loop
PHP for each loop is used to traverse array elements.
Syntax
foreach( $array as $var ){
//code to be executed
}
?>
Example:
<?php
$season=array("summer","winter","spring","autumn");
foreach( $season as $arr ){
echo "Season is: $arr<br />";
}
?>
PHP While Loop
The while loop is also called an Entry control loop because the condition is
checked before entering the loop body.
Syntax
while(condition){
//code to be executed
}
Alternative Syntax
while(condition):
//code to be executed
endwhile;
eg.,
<?php
Innahai Anugraham 27
BCA VI SEM PHP &MySQL Rajadhani Degree college
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
PHP do-while loop
It executes the code at least one time always because the condition is checked
after executing the code.
Syntax
do{
//code to be executed
}while(condition);
Example
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
PHP Break
The break keyword immediately ends the execution of the loop or switch
structure and program control resumes at the next statements outside the
loop/switch.
Syntax
jump statement;
break;
example:
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}?>
Innahai Anugraham 28
BCA VI SEM PHP &MySQL Rajadhani Degree college
PHP Arrays
Innahai Anugraham 29
BCA VI SEM PHP &MySQL Rajadhani Degree college
Easy to traverse: By the help of single loop, we can traverse all the
elements of an array.
Sorting: We can sort the elements of array.
PHP Array Types
There are 3 types of array in PHP.
Indexed Array
Associative Array
Multidimensional Array
PHP Indexed Array
PHP index is represented by number which starts from 0. PHP array elements
are assigned to an index number by default.
There are two ways to define indexed array:
1st way:
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
Eg.,
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Traversing PHP Indexed Array
We can easily traverse array in PHP using foreach loop.
Eg.,
<?php
$size=array("Big","Medium","Short");
foreach( $size as $s )
{
echo "Size is: $s<br />";
}
?>
Count Length of PHP Indexed Array
PHP provides count() function which returns length of an array.
Innahai Anugraham 30
BCA VI SEM PHP &MySQL Rajadhani Degree college
<?php
$size=array("Big","Medium","Short");
echo count($size);
?>
PHP Associative Array
We can associate name with each array elements in PHP using => symbol.
Innahai Anugraham 31
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 32
BCA VI SEM PHP &MySQL Rajadhani Degree college
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
4) PHP count() function
PHP count() function counts all elements in an array.
Syntax
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
echo count($season);
Innahai Anugraham 33
BCA VI SEM PHP &MySQL Rajadhani Degree college
?>
Output:
4
5) PHP sort() function
PHP sort() function sorts all the elements in an array.
Syntax
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
sort($season);
foreach( $season as $s )
{
echo "$s<br />";
}
?>
Output:
autumn
spring
summer
winter
6) PHP array_reverse() function
PHP array_reverse() function returns an array containing elements in reversed
order.
Syntax
array array_reverse ( array $array [, bool $preserve_keys = false ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
$reverseseason=array_reverse($season);
foreach( $reverseseason as $s )
{
echo "$s<br />";
}
?>
Output:
autumn
Innahai Anugraham 34
BCA VI SEM PHP &MySQL Rajadhani Degree college
spring
winter
summer
7) PHP array_search() function
PHP array_search() function searches the specified value in an array. It returns
key if search is successful.
Syntax
mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )
Example
<?php
$season=array("summer","winter","spring","autumn");
$key=array_search("spring",$season);
echo $key;
?>
Output:
2
8) PHP array_intersect() function
PHP array_intersect() function returns the intersection of two array. In other
words, it returns the matching elements of two array.
Syntax
array array_intersect ( array $array1 , array $array2 [, array $... ] )
Example
<?php
$name1=array("sonoo","john","vivek","smith");
$name2=array("umesh","sonoo","kartik","smith");
$name3=array_intersect($name1,$name2);
foreach( $name3 as $n )
{
echo "$n<br />";
}
?>
Output
sonoo
smith
9.PHP array_push() Function
The array_push() function inserts one or more elements to the end of an array.
Innahai Anugraham 35
BCA VI SEM PHP &MySQL Rajadhani Degree college
Syntax
array_push(array, value1, value2, ...)
Example
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
10. PHP array_pop() Function\
Delete the last element of an array:
Syntax: array_pop(array)
Example:
<?php
$a=array("red","green","blue");
array_pop($a);
print_r($a);
?>
11.PHP array_splice() Function:
New item in an array can be inserted with the help of array_splice() function of
PHP. This function removes a portion of an array and replaces it with something
else. If offset and length are such that nothing is removed, then the elements
from the replacement array are inserted in the place specified by the offset.
Syntax:
array array_splice ($input, $offset [, $length [, $replacement]])
eg.,
<?php
//Original Array on which operations is to be perform
$original_array = array( '1', '2', '3', '4', '5' );
echo 'Original array : ';
foreach ($original_array as $x)
{
echo "$x ";
}
echo "\n";
//value of new item
$inserted_value = '11';
Innahai Anugraham 36
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 37
BCA VI SEM PHP &MySQL Rajadhani Degree college
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: include1.php
<?php include("menu.html"); ?>
<h1>This is Main Page</h1>
Output:
Home |
PHP |
Java |
HTML
This is Main Page
PHP require
PHP require is similar to include, which is also used to include files. The only
difference is that it stops the execution of script if the file is not found whereas
include doesn't.
Syntax
There are two syntaxes available for require:
require 'filename';
Or
require ('filename');
Examples
Let's see a simple PHP require example.
File: menu.html
<a href="http://www.javatpoint.com">Home</a> |
<a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
<a href="http://www.javatpoint.com/java-tutorial">Java</a> |
<a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: require1.php
<?php require("menu.html"); ?>
<h1>This is Main Page</h1>
Output:
Home |
PHP |
Java |
HTML
This is Main Page
Innahai Anugraham 38
BCA VI SEM PHP &MySQL Rajadhani Degree college
intval():
intval(mixed $value, int $base = 10): int
By default base is 10, converting to decimal, it can also be 0x,0B,0 for
hexadecimal,binary and octal.
Example:
<?php
Innahai Anugraham 39
BCA VI SEM PHP &MySQL Rajadhani Degree college
floatval():
floatval(mixed $value): float
example:
<?php
echo floatval(42). PHP_EOL;
echo floatval(4.2). PHP_EOL;
echo floatval('42') . PHP_EOL;
echo floatval('99.90 Rs') . PHP_EOL;
echo floatval('$100.50') . PHP_EOL;
echo floatval('ABC123!@#') . PHP_EOL;
echo (true) . PHP_EOL; ;
echo (false) . PHP_EOL;
?>
O/P:
42
4.2
42
99.9
0
0
1
strval():
strval(mixed $value): string
<?php
echo strval(42). PHP_EOL;
echo strval(4.2). PHP_EOL;
echo strval(4.2E5) . PHP_EOL;
echo strval(NULL) . PHP_EOL;
echo (true) . PHP_EOL;
Innahai Anugraham 40
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 41
BCA VI SEM PHP &MySQL Rajadhani Degree college
UNIT-3
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input
as argument list and return value. There are thousands of built-in functions in
PHP. In PHP, we can define Conditional function, Function within Function and
Recursive function also.
PHP User-defined Functions
Syntax
function functionname(){
//code to be executed
}
Example:
<?php
function sayHello(){
echo "Hello PHP Function";
}
sayHello();//calling function
?>
PHP Function Arguments
PHP supports Call by Value (default), Call by Reference, Default argument
values and Variable-length argument list.
PHP Parameterized Function
PHP Parameterized functions are the functions with parameters. You can pass
any number of parameters inside a function. These passed parameters act as
variables inside your function.
example to pass two argument in PHP function.
<?php
function sayHello($name,$age){
echo "Hello $name, you are $age years old<br/>";
}
sayHello("Sonoo",27);
sayHello("Vimal",29);
sayHello("John",23);
?>
Output:
Hello Sonoo, you are 27 years old
Innahai Anugraham 42
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 43
BCA VI SEM PHP &MySQL Rajadhani Degree college
}
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
PHP Function: Returning Value
Example of PHP function that returns value:
<?php
function cube($n){
return $n*$n*$n;
}
echo "Cube of 3 is: ".cube(3);
?>
Output:
Cube of 3 is: 27
PHP Variable Length Argument Function
PHP supports variable length argument function. It means you can pass 0, 1 or n
number of arguments in function.
Example:
?php
function add(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum;
}
echo add(1, 2, 3, 4);
?>
Output:
10
PHP Recursive Function
Recursion is we call current function within function.
<?php
function factorial($n)
{
if ($n < 0)
Innahai Anugraham 44
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 45
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 46
BCA VI SEM PHP &MySQL Rajadhani Degree college
$timestamp = time();
echo($timestamp);
echo "\n";
echo(date("F d, Y h:i:s A", $timestamp));
?>
o/p: 1512486297
December 05, 2017 03:04:57 PM
PHP mktime() Function: The mktime() function is used to create the
timestamp for a specific date and time. If no date and time are provided, the
timestamp for the current date and time is returned.
Syntax:
mktime(hour, minute, second, month, day, year)
eg.,
<?php
echo mktime(23, 21, 50, 11, 25, 2017);
?>
The above code creates a time stamp for 25th Nov 2017,23 hrs 21mins 50secs.
o/p: 1511652110
Strings in PHP
PHP string is a sequence of characters i.e., used to store and manipulate text.
PHP supports only 256-character set and so that it does not offer native Unicode
support.
Creating and Declaring Strings
There are 4 ways to specify a string literal in PHP.
Single quoted:
We can create a string in PHP by enclosing the text in a single-quote. In single
quoted PHP strings, most escape sequences and variables will not be
interpreted. But, we can use single quote through \' and backslash through \\
inside single quoted PHP strings.
Example:
<?php
$str1='Hello text
multiple line
text within single quoted string';
$num=10;
$str2='Using double "quote" directly inside single quoted string $num';
$str3='Using escape sequences \n in single quoted string';
Innahai Anugraham 47
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 48
BCA VI SEM PHP &MySQL Rajadhani Degree college
It is a valid example
Newdoc syntax (since PHP 5.3): Newdoc is similar to the heredoc, but in
newdoc parsing is not done. It is also identified with three less than symbols
<<< followed by an identifier. But here identifier is enclosed in single-quote,
e.g. <<<'EXP'.
<?php
$str = <<<'DEMO'
Welcome to javaTpoint.
Learn with newdoc example.
DEMO;
echo $str;
echo '</br>';
echo <<< 'Demo' // Here we are not storing string content in variable str.
Welcome to javaTpoint.
Learn with newdoc example.
Demo;
?>
Output:
Welcome to javaTpoint. Learn with newdoc example.
Welcome to javaTpoint. Learn with newdoc example.
The difference between newdoc and heredoc is that - Newdoc is a single-
quoted string whereas heredoc is a double-quoted string.
String Functions
Innahai Anugraham 49
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 50
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 51
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 52
BCA VI SEM PHP &MySQL Rajadhani Degree college
UNIT-4
PHP Classes
PHP also supports the concept of object-oriented programming.
PHP classes are almost like functions but with a major different that classes
contain both variables and function, in a single format called object or can be
said Class is made from a collection of objects.
Syntax:
<?php
class myFirstClass {
var $ var _ a ;
var $ var _ b = " constant string " ;
Innahai Anugraham 53
BCA VI SEM PHP &MySQL Rajadhani Degree college
<?php
class Employee
{
/* Member variables */
var $name;
var $salary;
var $profile;
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
/* Member functions */
function set_name($new){
$this->name = $new;
}
?>
Creating Objects in PHP to access the class
Objects are created using new operator.
Eg.,
$employee_1 = new employees;
Eg.,
<!DOCTYPE html>
<html lang = " en ">
<head>
<meta charse t= " UTF ? 8 ">
<meta http ? equiv = " X ? UA ? Compatible " content = " IE = edge ">
<meta name = " viewport " content = " width = device - width, initial ? scale =
1 .0">
<title> PHP </title>
</head>
<body>
<?php
class employees {
/* Member variables */
var $name;
var $salary;
Innahai Anugraham 54
BCA VI SEM PHP &MySQL Rajadhani Degree college
var $profile;
/* Member functions */
function set_name($new){
$this->name = $new;
}
function get_name(){
echo $this->name ."<br/>";
}
function set_salary($new){
$this->salary = $new;
}
function get_salary(){
echo $this->salary ." <br/>";
}
function set_profile($new){
$this->profile = $new;
}
function get_profile(){
echo $this->profile ." <br/>";
}
}
$employee_1 = new employees;
$employee_1->set_name( "JOHN" );
$employee_1->set_salary( "10000" );
$employee_1->set_profile( "audit manager" );
$employee_1->get_name();
$employee_1->get_salary();
$employee_1->get_profile();
echo "<br/>";
?>
</body>
Innahai Anugraham 55
BCA VI SEM PHP &MySQL Rajadhani Degree college
</html>
Output:
JOHN
10000
audit manager
$ this Keyword
$ this keyword refers to the present object, and this keyword can only be used
inside a member function of a class. We can use $ this keyword in two ways
1) To add a value to the declared variable, we have to use $ this property inside
the set _ name function
Eg.,
<?php
class employee {
public $name;
var $salary;
function set_name($name) {
$this->name = $name;
}
function set_salary($salary) {
$this->salary = $salary;
}
}
$employee_1 = new employee();
$employee_1->set_name("JOHN");
$employee_1->set_salary(" $ 2000000"); ?>
2) In order to add a value to declared variable, the property of variable can be
changed directly.
Eg.,
<?php
class employee {
public $name;
var $salary;
}
$employee_1 = new employee();
$employee_1->name = " JOHN ";
$employee_1->salary = " $ 2000000 ";
Innahai Anugraham 56
BCA VI SEM PHP &MySQL Rajadhani Degree college
?>
Constructors
These are a special types of functions that are automatically called whenever an
object is created. These function are created by using the _construct ( )
keyword. The constructors have no Return Type, so they do not return anything
not even void.
Constructor types:
Default Constructor:It has no parameters, but the values to the default
constructor can be passed dynamically.
Parameterized Constructor: It takes the parameters, and also you can pass
different values to the data members.
Copy Constructor: It accepts the address of the other objects as a
parameter.
Syntax:
function __construct( $ parameter 1, $ parameter 2 ) {
$this->name = $ parameter 1;
$this->state = $ parameter 2;
}
<?php
class newconstructorclass
{
// Constructor
function __construct($new){
echo 'the constructor class has been initiated' ."<br/>" ;
$this->name = $new;
}
function get_name(){
echo $this->name ."<br/>";
}
}
// Create a new object
$obj = new newconstructorclass( " john " );
$obj -> get_name();
?>
Advantages of using Constructors:
1.Constructors provides the ability to pass parameters which are helpful in
automatic initialization of the member variables during creation time .
Innahai Anugraham 57
BCA VI SEM PHP &MySQL Rajadhani Degree college
2.The Constructors can have as many parameters as required and they can be
defined with the default arguments.
3.They encourage re-usability avoiding re-initializing whenever instance of the
class is created .
4.You can start session in constructor method so that you don’t have to start in
all the functions everytime.
5.They can call class member methods and functions.
6.They can call other Constructors even from Parent class.
Destructors
These are special functions that are automatically called whenever an object
goes out of scope or gets deleted. These functions are created by using the
_destruct ( ) keyword.
Syntax:
function __destruct() {
[ . . . . . . . . . . .]
[ . . . . . . . . . . .] }
Eg.,
<?php
class newdestructorclass
{
// Destructor
public function __destruct(){
echo 'The class ' . __CLASS__ . '" was automatically destroyed when the
created object does not have a scope to initiate';
}
Innahai Anugraham 58
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 59
BCA VI SEM PHP &MySQL Rajadhani Degree college
Constructors Destructors
PHP doesn’t support multiple inheritance but by using Interfaces in PHP or using
Traits in PHP instead of classes, we can implement it.
Innahai Anugraham 60
BCA VI SEM PHP &MySQL Rajadhani Degree college
Traits (Using Class along with Traits): The trait is a type of class which enables
multiple inheritance. Classec can extend only one other class but can extend more
than one trait at a time.
Syntax:
class child_class_name extends parent_class_name {
use trait_name;
...
...
child_class functions
}
Example:
<?php
// Class Geeks
class Geeks {
public function sayhello() {
echo "Hello";
}
}
// Trait forGeeks
trait forGeeks {
public function sayfor() {
echo " Geeks";
}
}
class Sample extends Geeks {
use forGeeks;
public function geeksforgeeks() {
echo "\nGeeksforGeeks";
}
}
$test = new Sample();
$test->sayhello();
$test->sayfor();
$test->geeksforgeeks();
?>
Innahai Anugraham 61
BCA VI SEM PHP &MySQL Rajadhani Degree college
Overloading in PHP
Function overloading in PHP is used to dynamically create properties and
methods. Function overloading contains same function name and that function
performs different task according to number of arguments. n PHP function
overloading is done with the help of magic function __call(). This function takes
function name and arguments.
Property and Rules of overloading in PHP:
1.All overloading methods must be defined as Public.
2.After creating the object for a class, we can access a set of entities that are
properties or methods not defined within the scope of the class.
3.Such entities are said to be overloaded properties or methods, and the process
is called as overloading.
4.For working with these overloaded properties or functions, PHP magic methods
are used.
6.Most of the magic methods will be triggered in object context except
__callStatic() method which is used in a static context.
Types of Overloading in PHP: There are two types of overloading in PHP.
Property Overloading
Method Overloading
Property Overloading: PHP property overloading is used to create dynamic
properties in the object context. Following operations are performed with
overloaded properties in PHP.
Setting and getting overloaded properties.
Evaluating overloaded properties setting.
Undo such properties setting.
Before performing the operations, we should define appropriate magic methods.
which are,
__set(): triggered while initializing overloaded properties.
__get(): triggered while using overloaded properties with PHP print statements.
__isset(): This magic method is invoked when we check overloaded properties
with isset() function
__unset(): Similarly, this function will be invoked on using PHP unset() for
overloaded properties.
Example.,
<?php
//
class GFG {
Innahai Anugraham 62
BCA VI SEM PHP &MySQL Rajadhani Degree college
// Function definition
public function __get($name) {
echo "Getting '$name: ";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
return null;
}
// Function definition
public function __isset($name) {
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}
Innahai Anugraham 63
BCA VI SEM PHP &MySQL Rajadhani Degree college
// Create an object
$obj = new GFG;
// Set value 1 to the object variable
$obj->a = 1;
echo $obj->a . "\n";
// Use isset function to check
// 'a' is set or not
var_dump(isset($obj->a));
// Unset 'a'
unset($obj->a);
var_dump(isset($obj->a));
echo $obj->declared . "\n\n";
echo "Private property are visible inside the class ";
echo $obj->getHidden() . "\n\n";
echo "Private property are not visible outside of class\n";
echo $obj->hidden . "\n";
?>
Output:
Setting 'a' to '1'
Getting 'a: 1
Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)
1
Innahai Anugraham 64
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 65
BCA VI SEM PHP &MySQL Rajadhani Degree college
// print Parent
$p->geeks();
// Print child
$c->geeks();
?>
PHP Form Handling:
The form request may be get or post.
PHP Get Form
Get request is the default form request. The data passed through get request is
visible on the URL browser so it is not secured. You can send limited amount of
data through get request.
Innahai Anugraham 66
BCA VI SEM PHP &MySQL Rajadhani Degree college
Eg.,
File: form1.html
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>
PHP Post Form
Post request is widely used to submit form that have large amount of data such as
file upload, image upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it is
secured.
File: form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password"
name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];//receiving password field value in $password
variable
echo "Welcome: $name, your password is: $password";
?>
PHP Form Validation
PHP methods and arrays used in form processing are:
1.isset(): This function is used to determine whether the variable or a form control
is having a value or not.
Innahai Anugraham 67
BCA VI SEM PHP &MySQL Rajadhani Degree college
Eg.,
If (isset($_POST['submit']))
{
$number= $_GET["number"];
}
2.$_GET[]: It is used the retrieve the information from the form control through
the parameters sent in the URL. It takes the attribute given in the url as the
parameter.
e.g, $number= $_GET["number"];
3.$_POST[]: It is used the retrieve the information from the form control through
the HTTP POST method. IT takes name attribute of corresponding form control
as the parameter.
Eg., $number= $_POST["number"];
4.$_REQUEST[]: It is used to retrieve an information while using a database.
5. $_SERVER: $_SERVER is a PHP super global variable which holds
information about headers, paths,request method and script locations.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
Innahai Anugraham 68
BCA VI SEM PHP &MySQL Rajadhani Degree college
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows
dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
Innahai Anugraham 69
BCA VI SEM PHP &MySQL Rajadhani Degree college
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Innahai Anugraham 70
BCA VI SEM PHP &MySQL Rajadhani Degree college
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Innahai Anugraham 71
BCA VI SEM PHP &MySQL Rajadhani Degree college
MYSQL INTRODUCTION:
MySQL is a relational database management system based on the Structured
Query Language, which is the popular language for accessing and managing the
records in the database. MySQL is open-source and free software under the
GNU license. It is supported by Oracle Company. It is developed, marketed, and
supported by MySQL AB, a Swedish company, and written in C programming
language and C++ programming language.
MySQL is a Relational Database Management System (RDBMS) software that
provides many things, which are as follows:
It allows us to implement database operations on tables, rows, columns,
and indexes.
It defines the database relationship in the form of tables (collection of
rows and columns), also known as relations.
It provides the Referential Integrity between rows or columns of various
tables.
It allows us to updates the table indexes automatically.
It uses many SQL queries and combines useful information from multiple
tables for the end-users.
The process of MySQL environment is the same as the client-server model.
The core of the MySQL database is the MySQL Server. This server is available
as a separate program and responsible for handling all the database instructions,
statements, or commands. The working of MySQL database with MySQL
Server are as follows:
MySQL creates a database that allows you to build many tables to store
and manipulate data and defining the relationship between each table.
Innahai Anugraham 72
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 73
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 74
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 75
BCA VI SEM PHP &MySQL Rajadhani Degree college
The following list describes the common string data types in MySQL −
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 the sorts and
comparisons on the 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.
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.
The MySQL Varchar Data Type
The MySQL VARCHAR data type is used to store variable-length character
strings, having a length up to 65,535 bytes.
In MySQL, when you store text in a VARCHAR column, it needs a little extra
space to keep track of how long the text is. This extra space can be either 1 or 2
Innahai Anugraham 76
BCA VI SEM PHP &MySQL Rajadhani Degree college
bytes, depending on the length of the text. If the text is short (less than 255
characters), it uses 1 byte for length. For longer text, it uses 2 bytes.
The total size of data plus the length info cannot exceed 65,535 bytes for a row
in a table.
MySQL - Boolean Datatype
MySQL considers the value 0 as FALSE and 1 as TRUE. We can also store
NULL values using the TINYINT datatype. The Boolean values (such as TRUE
and FALSE) are not case-sensitive.
Spatial Data Type
It is a special kind of data type which is used to hold various geometrical and
geographical values.
Innahai Anugraham 77
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 78
BCA VI SEM PHP &MySQL Rajadhani Degree college
You can also access MySQL Command Line Client from Command Prompt.
For this:
Open Command Prompt.
Navigate to the bin folder. For example: cd C:\Program
Files\MySQL\MySQL Server 8.0\bin
Run the mysql -u root -p command.
Enter the password.
Innahai Anugraham 79
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 80
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 81
BCA VI SEM PHP &MySQL Rajadhani Degree college
Enter the table name, number of columns, and click on Go. A message will
show that the table is created successfully.
Innahai Anugraham 82
BCA VI SEM PHP &MySQL Rajadhani Degree college
Now enter the field name, type, their size, and any constraint here and save it.
Innahai Anugraham 83
BCA VI SEM PHP &MySQL Rajadhani Degree college
The table is created successfully. We can make changes in the table from here.
Innahai Anugraham 84
BCA VI SEM PHP &MySQL Rajadhani Degree college
Procedure oriented
mysqli.connect(servername,username,password,databasename)
Database name is optional
eg.,
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Object oriented
mysqli(servername,username,password,dbname)
Dbname is optional
eg.,
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Innahai Anugraham 85
BCA VI SEM PHP &MySQL Rajadhani Degree college
MySQLi Object-Oriented:
$conn->close();
MySQLi Procedural:
mysqli_close($conn);
PDO:
$conn = null;
Innahai Anugraham 86
BCA VI SEM PHP &MySQL Rajadhani Degree college
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
Innahai Anugraham 87
BCA VI SEM PHP &MySQL Rajadhani Degree college
mysqli_close($conn);
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
PHP MySQL Create Table
Example
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
Innahai Anugraham 88
BCA VI SEM PHP &MySQL Rajadhani Degree college
Innahai Anugraham 89
BCA VI SEM PHP &MySQL Rajadhani Degree college
$id=2;
$name="Rahul";
$salary=80000;
$sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";
if(mysqli_query($conn, $sql)){
echo "Record updated successfully";
}else{
echo "Could not update record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
$id=2;
$sql = "delete from emp4 where id=$id";
if(mysqli_query($conn, $sql)){
echo "Record deleted successfully";
Innahai Anugraham 90
BCA VI SEM PHP &MySQL Rajadhani Degree college
}else{
echo "Could not deleted record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
PHP MySQL Select Query
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
Connected successfully
EMP ID :1
EMP NAME : ratan
Innahai Anugraham 91
BCA VI SEM PHP &MySQL Rajadhani Degree college
query(Mandatory)
2
This is a string value representing the query to be executed.
mode(Optional)
This is a integer value representing the result mode. You can
3
pass MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT as values to this
parameter.
mysqli_num_rows($retval): returns number of tuples stored in the object
retval or num of rows in the result set if a query.
<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
Innahai Anugraham 92
BCA VI SEM PHP &MySQL Rajadhani Degree college
// Associative array
$row = mysqli_fetch_assoc($result);
printf ("%s (%s)\n", $row["Lastname"], $row["Age"]);
mysqli_close($con);
?>
Innahai Anugraham 93