0% found this document useful (0 votes)
16 views

Note

Thank you

Uploaded by

Chandana Gouda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Note

Thank you

Uploaded by

Chandana Gouda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT – II

Program Control
Just as with most other programming languages there are a number of conditional and iteration
constructs in PHP. There are if and switch, and while, do while, for, and foreach loops.

if . . . else
In this syntax the condition to test is contained within () brackets with the body contained in {}
blocks. Optional else if statements can follow, with an else ending the branch. The below code
use a condition to set a greeting variable, depending on the hour of the day.
if ( $hourOfDay > 6 && $hourOfDay < 12 )
{
$greeting = "Good Morning";
}
else if ($hourOfDay == 12)
{
$greeting = "Good Noon Time";
}
else
{
$greeting = "Good Afternoon or Evening";
}

switch . . . case
The switch statement is similar to a series of if . . . else statements.
switch ($artType)
{
case "PT":
$output = "Painting";
break;
case "SC":
$output = "Sculpture";
break;
default:
$output = "Other";
}

Prof. Ashish. D. Revankar PHP & MYSQL 1|Page


while and do . . . while
The while loop and the do . . . while loop are quite similar. Both will execute nested statements
repeatedly as long as the while expression evaluates to true. In the while loop, the condition is
tested at the beginning of the loop; in the do ... while loop the condition is tested at the end of
each iteration of the loop.
Eg : //while loop
$count = 0;
while ($count < 10)
{
echo $count;
$count++;
}
//do-while
$count = 0;
do
{
echo $count;
$count++;
} while ($count < 10);

For loop

The for loop in PHP has the same syntax as the for loop in JavaScript. The for loop contains the
same loop initialization, condition, and post-loop operations as in JavaScript.
for ($count=0; $count < 10; $count++)
{
echo $count.’<br />’;
}
The foreach loop is used for iterating through arrays or list of elements.

Alternate Syntax for Control Structures


PHP has an alternative syntax for most of its control structures (namely, the if, while, for,
foreach, and switch statements). In this alternate syntax, the colon (:) replaces the opening curly
bracket, while the closing brace is replaced with endif;, endwhile;, endfor;, endforeach;, or
endswitch;. It improves the readability of PHP code.
<?php if ($userStatus == "loggedin") : ?>
<a href="account.php">Account</a>
<?php else : ?>
<a href="login.php">Login</a>
<a href="register.php">Register</a>
<?php endif; ?>
Prof. Ashish. D. Revankar PHP & MYSQL 2|Page
Arrays
PHP supports arrays, like most other programming languages. An array is a data structure that allows
the programmer to collect a number of related elements together in a single variable. In PHP an array
is an ordered map, which associates each value in the array with a key. An array of key-value pair,
containing the days of the week can be visualized as follows –

Array keys in most programming languages are limited to integers, start at 0, and go up by 1. In PHP,
keys can be either integers or strings.
Array values are not restricted to integers and strings. They can be any object, type, or primitive
supported in PHP.

Defining and Accessing an Array

Declaration of an empty array named days:


$days = array()
Two different ways of defining an array –
Arrayvariable = array(elements separated by comma);
Arrayvariable = [elements separated by comma];
Eg -
$days = array(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”);
$days = [“Mon”,”Tue”,”Wed”,”Thu”,”Fri”]; // alternate syntax
$count=array(“one”,”two”,3,4);
$count = [“one”,”two”,3,4];
In these examples, because no keys are explicitly defined for the array, the default key values are 0, 1,
2, . . . , n.
The array elements can also be defined individually using the square bracket notation:
$days = array();
$days[0] = "Mon";
$days[1] = "Tue";
$days[2] = "Wed";

Prof. Ashish. D. Revankar PHP & MYSQL 3|Page


// also alternate approach
$daysB = array();
$daysB[] = "Mon";
$daysB[] = "Tue";
$daysB[] = "Wed";

Arrays are dynamically sized - elements are added to or deleted from the array during run-time.
Elements within an array are accessed using the familiar square bracket notation.
Arrayvariable[index];
The code below echoes the value of our $days array for the key=1, which results in
output of Tue.
echo "Value at index 1 is ". $days[1]; // index starts at zero
In PHP, keys can be explicitly defined along with the values. This allows us to use keys other than the
classic 0, 1, 2, . . . , n to define the indexes of an array. The array
$days = array(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”); can be defined more explicitly by specifying the
keys and values as
$days = array(0 => "Mon", 1 => "Tue", 2 => "Wed", 3 => "Thu", 4=> "Fri");
Where 0,1,2,… are the keys and “Mon”,”Tue”,… are the values.
These types of arrays in PHP are generally referred to as associative arrays. Keys must be either
integer or string values, but the values can be any type of PHP data type, including other arrays.
In the above example, the keys are strings (for the weekdays) and the values are weather forecasts for
the specified day in integer degrees. To access an element in an associative array,
simply use the key value rather than an index:
echo $forecast["Wed"]; // this will output 52

Multidimensional Arrays

PHP also supports multidimensional arrays, an array within another array. It can be defined as -
$month = array
(
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri")
);
echo $month[0][3]; // outputs Thu
OR
$cart = array();
$cart[] = array("id" => 37, "title" => "Burial at Ornans", "quantity" => 1);
$cart[] = array("id" => 345, "title" => "The Death of Marat", "quantity" => 1);
$cart[] = array("id" => 63, "title" => "Starry Night", "quantity" => 1);
echo $cart[2]["title"]; // outputs Starry Night

Iterating through an Array

Prof. Ashish. D. Revankar PHP & MYSQL 4|Page


Iteration through the array contents is performed using the loops. Count() function is used to check the
size of the array.
When there is nonsequential integer keys or strings as keys (i.e., an associative array), the accessing of
elements can’t be done using a $i, in such cases foreach loop is used. Foreach loop iterates till the end
of array and stops. Each value can be accessed during the iterations, or both the key and value can be
accessed, as shown below.
// while loop
$i=0;
while ($i < count($days)) {
echo $days[$i] . "<br>";
$i++;
}
// do while loop
$i=0;
do {
echo $days[$i] . "<br>";
$i++;
} while ($i < count($days));
// for loop
for ($i=0; $i<count($days); $i++) {
echo $days[$i] . "<br>";
}
// foreach: iterating through the values
foreach ($forecast as $value) {
echo $value . "<br>";
}
// foreach: iterating through both the values and the keys
foreach ($forecast as $key => $value) {
echo "day" . $key . "=" . $value;
}

Adding and Deleting Elements

In PHP, arrays are dynamic. The arrays can grow or shrink in size. An element can be added to an
array simply by using a key/index that hasn’t been used.
$days[5] = "Sat";
Since there is no current value for key 5, the array grows by one, with the new key/value pair added to
the end of our array. If the key had a value already, the new value replaces the value at that key.
As an alternative to specifying the index, a new element can be added to the end of any existing array
by -
$days[ ] = "Sun";
The advantage to this approach is that you don’t have to remember the last index key used.
$days = array("Mon","Tue","Wed","Thu","Fri");
Prof. Ashish. D. Revankar PHP & MYSQL 5|Page
$days[7] = "Sat";
print_r($days);
The print_r() - will display the non-NULL elements of the array, as shown below -
Array ([0] => Mon [1] => Tue [2] => Wed [3] => Thu [4] => Fri [7] => Sat)
The NULL value are not displayed.
Elements can be deleted from the array explicitly by using the unset() function –
$days = array("Mon","Tue","Wed","Thu","Fri");
unset($days[2]);
unset($days[3]);
print_r($days); // outputs: Array ( [0] => Mon [1] => Tue [4] => Fri )
The Null values in arrays can be removed and array is reindexed by using the array_values()
function.
$b = array_values($days);
print_r($b); // outputs: Array ( [0] => Mon [1] => Tue [2] => Fri )
// Array is reindexed.
print_r($days) // outputs: Array ( [0] => Mon [1] => Tue [4] => Fri )

Checking If a Value Exists

It is possible to check if an array index contains a value or NULL by using the isset() function. The
returns true if a value has been set, and false otherwise.
$days = array (1 => "Tue", 3 => "Wed", 5 => "Thurs");
if (isset($days[0]))
{
// The code below will never be reached since $days[0] is not set!
echo "Monday";
}
if (isset($days[1]))
{
echo "Tuesday";
}

Array Sorting – Array Operations

There are many built-in sort functions, which sort by key or by value in PHP.
sort(arrayname); - sort the array in ascending order by its values. The array itself is sorted.
$days = array("Mon","Tue","Wed","Thu","Fri");
sort($days);
print_r($days); // outputs: Array ([0] => Fri [1] => Mon [2] => Thu [3] => Tue [4] => Wed)

sort() function loses the association between the values and the keys.
asort(arrayname) – sort the array in ascending order by its values, association is maintained.
Eg –
Prof. Ashish. D. Revankar PHP & MYSQL 6|Page
asort($days);
print_r($days); // outputs: Array ([4] => Fri [0] => Mon [3] => Thu [1] => Tue [2] => Wed)

More Array Operations


some key array functions are –
array_keys($Arrayname)
array_values($Arrayname)
array_rand($Arrayname, $num=1)
array_reverse($Arrayname)
array_walk($Arrayname, $callback, $optionalParam)
in_array($value, $Arrayname)
shuffle($Arrayname)
array_keys($Arrayname): This method returns an indexed array with the values being the keys of
$Arrayname.
Eg : print_r(array_keys($days))
outputs - Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 )

array_values($Arrayname): This method returns an indexed array with the values being the values
of $ Arrayname.
Eg: print_r(array_values($days))
Outputs - Array ( [0] => Mon [1] => Tue [2] => Wed [3] => Thu [4] => Fri )

array_rand($Arrayname, $num=1): This function returns an array of, as many random keys as are
requested. If you only want one, the key itself is returned;
otherwise, an array of keys is returned.
For example, print_r(array_rand($days,2))
might output: Array (3, 0)

array_reverse($Arrayname): This method returns $Arrayname in reverse order. The passed


$Arrayname is not altered, a new array of reversed elements is returned.
For example, print_r(array_reverse($days))
outputs: Array ( [0] => Fri [1] => Thu [2] => Wed [3] => Tue [4] => Mon )

array_walk($Arrayname, $callback, $optionalParam): This method allows to call a method


($callback), for each value in $Arrayname. One or more additional parameters can also be sent to the
function.
The $callback function typically takes two parameters by default, the value, and the key of the array.
Eg - prints the value of each element in the array is shown below.
$someA = array("hello", "world");
array_walk($someA, "doPrint");
function doPrint($value,$key)
{
echo $key . ": " . $value . “<br />”;
}

Prof. Ashish. D. Revankar PHP & MYSQL 7|Page


Output:
0 : hello
1 : world

Additional parameters can be sent to the function as shown below –

$someA = array("hello", "world");


array_walk($someA, "doPrint",”one”,”two”,3);
function doPrint($value,$key,$t1,$t2,$t3)
{
echo $key . ": " . $value . “<br />”;
echo “$t1 $t2 $t3 <br />”,
}
Output:
0 : hello
one two 3
1 : world
one two 3

in_array($value, $arrayname): This method search the array $ arrayname for a value ($value). It
returns true if value is found, and false otherwise.
if(in_array(“Wed”,$days))
echo “Element found”;
else
echo “Element not found”;

shuffle($arrayname): This method shuffles $arrayname in random order and makes it an indexed
array.
shuffle($days);
print_r($days); // Array ( [0] => Thu [1] => Fri [2] => Wed [3] => Mon [4] => Tue)
shuffle($days);
print_r($days); // Array ( [0] => Tue [1] => Mon [2] => Thu [3] => Wed [4] => Fri )

Include Files
PHP have facility to include or insert content from one file into another. Include files provide a
Prof. Ashish. D. Revankar PHP & MYSQL 8|Page
mechanism for reusing both markup and PHP code.
PHP provides four different statements for including files, as shown below.
include "somefile.php";
include_once "somefile.php";
require "somefile.php";
require_once "somefile.php";
The difference between include and require lies in what happens when the specified file cannot
be included. With include, a warning is displayed and then execution continues. With require, an
error is displayed and execution stops. The include_once and require_once statements work just
like include and require but if the requested file has already been included once, then it will not
be included again.

UNIT – III
Functions
Prof. Ashish. D. Revankar PHP & MYSQL 9|Page
A function in PHP contains a small bit of code that accomplishes a task. These functions can be
made to behave differently based on the values of their parameters. It exist all on its own, and is
called from anywhere that needs to make use of them.
In PHP there are two types of function: user-defined functions and built-in functions.
A user-defined function is one that the programmer define. A built-in function is one of the
functions that come with the PHP environment. One of the real strengths of PHP is its rich
library of built-in functions.

Function Syntax
The PHP function uses ‘function’ keyword followed by the function’s name, round ( )
brackets for parameters, and then the body of the function inside curly { } brackets. Functions can
return values to the caller, or not return a value.

Syntax:
function functionname(parameter list)
{
}

Eg:
function getSum()
{
$x=5;$y=6;
$z= $x+$y;
echo $z;
}

A function called getNiceTime(), which will return a formatted string containing the current
server time

function getNiceTime()
{
return date("H:i:s");
}

Calling a Function
To call a function you must use its name with the () brackets. Since getNiceTime() returns a
Prof. Ashish. D. Revankar PHP & MYSQL 10 | P a g e
string, you can assign that return value to a variable, or echo that return value directly, as shown
below.
$output = getNiceTime();
OR
echo getNiceTime();
If the function doesn’t return a value, you can just call the function:

getSum();

<?php
function getSum($x,$y)
{
$z= $x+$y;
return $z; // return $x+$y;
}
$ sum =getSum(5,6);
Echo $sum;
?>

Parameters

Parameters are the mechanism by which values are passed into functions, and there are some
complexities that allow us to have multiple parameters, default values, and to pass objects by
reference instead of value. Parameters, being a type of variable, must be prefaced with a $
symbol like any other PHP variable
<?php
function getSum($x,$y)
{
$z= $x+$y;
echo $z;
}
getSum(5,6);
?>

Parameter Default Values

In PHP, parameter default values can be set for any parameter in a function. However, once
you start having default values, all subsequent parameters must also have defaults.

<?php
function getSum($x,$y=10)
{

Prof. Ashish. D. Revankar PHP & MYSQL 11 | P a g e


$z= $x+$y;
return $z; // return $x+$y;
}
Echo “sum of 5 and6 is “.getSum(5,6);

Echo “<br />sum of 15 and 10 is “.getSum(15);


Echo “<br />sum of 12 and 14 is “.getSum(12,14);
Echo “<br />sum of 25 and 10 is “.getSum(25);
?>

Output:

sum of 5 and6 is 11
sum of 15 and 10 is 25
sum of 12 and 14 is 26
sum of 25 and 10 is 35

Even if 2nd parameter value is not passed to the function, the default value 10 is taken. If the
value is passed, the default will be overridden by whatever that value was.

Passing Parameters by Reference

By default, arguments passed to functions are passed by value in PHP. This means that PHP
passes a copy of the variable so if the parameter is modified within the function, it does not
change the original.
In the below example, notice that even though the function modifies the parameter value, the
contents of the variable passed to the function remain unchanged after the function has been
called.

function changeParameter($arg)
{
$arg += 300;
echo "arg=" . $arg;
}

$initial = 15;

echo "<br/>initial=" . $initial;


changeParameter($initial);
echo "<br/>initial=" . $initial; // value not changed
Output:
initial=15
Prof. Ashish. D. Revankar PHP & MYSQL 12 | P a g e
arg =315
initial=15

PHP allows arguments to functions to be passed by reference, which will allow a function to
change the contents of a passed variable. A parameter passed by reference points the local
variable to the same place as the original, so if the function changes it, the original variable is
changed as well. The mechanism in PHP to specify that a parameter is passed by reference is to
add an ampersand (&) symbol next to the parameter name in the function definition.

Eg:
function changeParameter(&$arg)
{
$arg += 300;
echo "arg=" . $arg;
}
$initial = 15;
echo "<br/>initial=" . $initial;
changeParameter($initial);
echo "<br/>initial=" . $initial; // value changed

Output:
initial=15
arg =315
initial=315

Variable Scope within Functions

All variables defined within a function have function scope, ie. they are only accessible within
the function.
Unlike in other language, in PHP any variables created outside of the function in the main script
are unavailable within a function. For instance, in the following example, the output of the echo
within the function is 0 and not 56 since the reference to $count within the function is assumed to
be a new
variable named $count with function scope.
$count= 56;
function testScope() {
echo $count; // outputs 0 or generates run-time warning/error
}
testScope();
echo $count; // outputs 56
The program results in run – time error
Prof. Ashish. D. Revankar PHP & MYSQL 13 | P a g e
PHP allow variables with global scope to be accessed within a function using the global
keyword.
<?php
$count= 56;
function testScope() {
global $count;
echo $count;
}
testScope();
echo $count;
?>
Output:
56
56

Strings in PHP
PHP string is a sequence of characters i.e., used to store and manipulate text.
Prof. Ashish. D. Revankar PHP & MYSQL 14 | P a g e
1.single quoted : We can create a string in PHP by enclosing the text in a single-quote. It is the
easiest way to specify string in PHP.
Eg: $str='Hello text within single quote';
2. double quoted : In PHP, we can specify string through enclosing text within double quote also.
But escape sequences and variables will be interpreted using double quote PHP strings.
eg: $num1=10;
echo "Number is: $num1";

PHP String Functions

1. String Length: strlen() : This function returns the length of a string.


Example : $text = "This is a test string.";
$length = strlen($text);
2. String Position: strpos() : This function finds the position of a substring in a string.
Example : $pos = strpos($text, "test");
3. Substring Function: substr() : This function extracts a substring from a string.
Example: $substring = substr($text, 0, 5);
4. String Replace: str_replace() : This function replaces all occurrences of a substring with
another substring.
Example:$newText = str_replace("World", "Universe", $text);
5. Convert String to Uppercase: strtoupper(): This converts a string to all uppercase characters.
Example: $uppercase = strtoupper($text);
6. Convert String to Lowercase: strtolower(): This function converts a string to lowercase.
Example: $lowercase = strtolower($text);
7. Trim String: trim(): This removes whitespace or other characters from the beginning and end
of a string.
Example:$trimmed = trim($text);
8. String Reverse: strrev(): This function reverses the order of a string.
Prof. Ashish. D. Revankar PHP & MYSQL 15 | P a g e
Example:$reversed = strrev($text);
9. String Compare: strcmp() : This function compares two strings and returns 0 if they are equal,
a positive number if the first string is greater, and a negative number if the second
string is greater.
Example: $string1 = "apple"; $string2 = "banana";
$result = strcmp($string1, $string2);

Class & Objects in PHP


Class:

Prof. Ashish. D. Revankar PHP & MYSQL 16 | P a g e


A class is an entity that determines how an object will behave and what the object will contain. In
other words, it is a blueprint or a set of instruction to build a specific type of object.

Object:
A class defines an individual instance of the data structure. We define a class once and then make
many objects that belong to it. Objects are also known as an instance.

Syntax:
<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>
Object Properties:
Once you have instances of an object, you can access and modify the properties of each one
separately using the variable name and an arrow (->).
Example of class and object:
<?php
class demo
{
private $a= "hello javatpoint";
public function display()
{
echo $this->a;

Prof. Ashish. D. Revankar PHP & MYSQL 17 | P a g e


}
}
$obj = new demo();
$obj->display();
?>

Inheritance:
It is a concept of accessing the features of one class from another class. If we inherit the class
features into another class, we can access both class properties. We can extends the features of a
class by using 'extends' keyword.
Inheritance has three types, single, multiple and multilevel Inheritance.
PHP supports only single inheritance, where only one class can be derived from single parent
class.
We can simulate multiple inheritance by using interfaces.

Example
<?php
class a
{
function fun1()
{
echo "javatpoint";
}
}

class b extends a
{

Prof. Ashish. D. Revankar PHP & MYSQL 18 | P a g e


function fun2()
{
echo "SSSIT";
}
}

$obj= new b();


$obj->fun1();

?>

Constructors:
PHP 5 allows developers to declare constructor methods for classes.
Constructor is suitable for any initialization that the object may need before it is used.
We can design constructor using "__construct" or same name as class name.
Parent constructors are not called implicitly if the child class defines a constructor. In order to run
a parent constructor, a call to parent::__construct().
Example
<?php
class Example
{
public function __construct()
{
echo "Hello kle bca dwd";
}
}
$obj = new Example();
Prof. Ashish. D. Revankar PHP & MYSQL 19 | P a g e
$obj = new Example();
?>
Destructors:
P 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++.
The destructor method will be called as soon as all references to a particular object are removed
or when the object is explicitly destroyed in any order in shutdown sequence.
We create destructor by using "__destruct" function.
Example
<?php
class Example
{
public function __construct()
{
echo "Hello kle bca dwd";
}
pubfunction __destruct()
{
echo "destroy.....";
}

}
$obj = new Example();
$obj = new Example();
?>

PHP Form Handling

Prof. Ashish. D. Revankar PHP & MYSQL 20 | P a g e


$_GET and $_POST Superglobal arrays
• PHP uses special predefined associative arrays called superglobal variables that allow the
programmer to easily access HTTP headers, query string parameters, and other commonly
needed information.
• They are called superglobal because they are always in scope, and always defined.
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.

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.
You can send large amount of data through post request.
• Let's see a simple example to receive data from post request in PHP.
• POST method also supports multipart form-data upload which is used for file upload.
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.
Prof. Ashish. D. Revankar PHP & MYSQL 21 | P a g e
• The data passed through post request is not visible on the URL browser so it is secured.
You can send large amount of data through post request.
• Let's see a simple example to receive data from post request in PHP.
• POST method also supports multipart form-data upload which is used for file upload.

Superglobal Arrays
PHP uses special predefined associative arrays called superglobal variables. It allows the programmer
to easily access HTTP headers, query string parameters, and other commonly needed information.
They are called superglobal because these arrays are always accessible, from a function , class or file,
without using the global keyword.

UNIT – IV

Prof. Ashish. D. Revankar PHP & MYSQL 22 | P a g e


Database Handling Using PHP with MySQL

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.
Database :A database is an application that stores the organized collection of records. It can be
accessed and manage by the user very easily. It allows us to organize data into tables, rows,
columns, and indexes to to find the relevant information very quickly.
MySQL is currently the most popular database management system software used for managing
the relational database. It is open-source database software,e relevant information very quickly.
MySQL Works
MySQL follows the working of Client-Server Architecture. This model is designed for the end-
users called clients to access the resources from a central computer known as a server using
network services.
Here, the clients make requests through a graphical user interface (GUI), and the server will give
the desired output as soon as the instructions are matched. The process of MySQL environment is
the same as the client-server model.

MySQL Commands
1. MySQL Create Database
create database db1;

Prof. Ashish. D. Revankar PHP & MYSQL 23 | P a g e


2. MySQL Select/Use Database
use db1;
3) MySQL Create Query
CREATE TABLE customers (id int(10), name varchar(50), city v
archar(50), PRIMARY KEY (id ) );
4) MySQL Alter Query
ALTER TABLE customers ADD age varchar(50);
5) MySQL Insert Query
insert into customers values(101,'rahul','delhi');
6) MySQL Update Query
update customers set name='bob', city='london' where id=101;
7) MySQL Delete Query
delete from customers where id=101;
8) MySQL Select Query
SELECT * from customers;

PHP MySQL Connect and Selecting the Database


mysql_connect()
PHP mysql_connect() function is used to connect with MySQL database.
It returns resource if connection is established or null.

<?php

Prof. Ashish. D. Revankar PHP & MYSQL 24 | P a g e


$host = 'localhost:3306';
$user = '';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($conn);
?>

Executing Simple Queries


mysql_query()
PHP mysql_query() function is used to create table. Since PHP
5.5, mysql_query() function is deprecated.

<?php
$host = 'localhost:3306';
$user = ‘root';
$pass = ‘ ';
$conn = mysql_connect($host, $user, $pass);
if(! $conn )
{

Prof. Ashish. D. Revankar PHP & MYSQL 25 | P a g e


die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';

$sql = "create table emp5(id INT AUTO_INCREMENT,name VARCHAR(20) N


OT NULL,emp_salary INT NOT NULL,primary key (id))";
if(mysqli_query($sql ,$conn))
{
echo "Table emp5 created successfully";
}
else{ echo "Could not create table: ". mysqli_error($conn); }

mysqli_close($conn);
?>

Retrieving Query Results


PHP mysql_query() function is used to execute select query. Since PHP 5.5, mysql_query() function
is deprecated.

There are two other MySQLi functions used in select query.

o mysqli_num_rows(mysqli_result $result): returns number of rows.


o mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each
key of the array represents the column name of the table. It return NULL if there are no
more rows.

<?php
$host = 'localhost:3306';
Prof. Ashish. D. Revankar PHP & MYSQL 26 | P a g e
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';

$sql = 'SELECT * FROM emp4';


$retval=mysqli_query($conn, $sql);

if(mysqli_num_rows($retval) > 0){


while($row = mysqli_fetch_assoc($retval)){
echo "EMP ID :{$row['id']} <br> ".
"EMP NAME : {$row['name']} <br> ".
"EMP SALARY : {$row['salary']} <br> ".
"--------------------------------<br>";
} //end of while
}else{
echo "0 results";
}
mysqli_close($conn);
?>
.

Updating Records with PHP

Prof. Ashish. D. Revankar PHP & MYSQL 27 | P a g e


PHP mysql_query() function is used to update record in a table. Since PHP
5.5, mysql_query() function is deprecated.

<?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/>';

$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);
?>

Prof. Ashish. D. Revankar PHP & MYSQL 28 | P a g e

You might also like