Professional Documents
Culture Documents
Unit 1
Unit 1
by
A.kiran Kumar
CMRTC
Assistant Professor
UNIT- I
PHP Syntax
<?php
?>
PHP Hello world Ex
The program shown below is a basic PHP application that outputs the words “Hello World!”
When viewed in a web browser.
<?php
echo "Hello world";
?>
Ex To demonstrate inserting php code in html
<html>
<body>
<?php
?>
</body>
</html>
Set Up PHP on Your Own PC
However, if your server does not support PHP, you must:
•install a web server
•install PHP
•install a database, such as MySQL
Webserver To install in your PC or Laptop
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is
available for all operating systems.
•WAMP for Windows
•LAMP for Linux
•XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform:
PHP variables
Variable: A variable is the name given to the memory location used to store values at the time
of program execution.
PHP is loosely typed language that’s why we can store variables without data types. PHP
automatically converts the variable to the correct data type, depending on its value.
Syntax :
$variablename=value;
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number or special symbols.
A variable name cannot contain spaces.
A variable name can only contain alphabets, numbers and underscore symbol _.
Variable names are case-sensitive ($age and $AGE are two different variables)
PHP Variable: Declaring string, integer, and float
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
PHP Variable Scope:
Variable Scope: The scope of a variable is the portion of the program within
which it is defined and can be accessed."
Depending on the scopes, PHP has three variable scopes:
1. Local Variable
2. Global variable
3. Static variable
Local Variable: The variables declared within a function are called local variables to that function and
have their scope only in that particular function.
Local Variables we can access within the function where we declared. we cannot access outside the
function.
<?php
function local_var()
local_var();
<?php
$num = 10;
function global_var()
global $num;
}
Static variables: It is a feature of PHP to delete the variable, once it completes its execution and memory
is freed. Sometimes we need to store a variable even after completion of function execution.
The variable which is declared with the static keyword is called static variable.
Static variables can maintain previous values .We can assign the values only one time in to static variable.
output: 6373
PHP DATA TYPES
Data type: Types define the type of data a variable can store.
PHP allows eight different types of data types
PHP supports 8 primitive data types that can be categorized further in 3 types:
1.Scalar Types (predefined)
2.Compound Types (user-defined)
3.Special Types
Scalar Types
A variable is a scalar when it holds a single value of the type integer, float, string, or boolean.
There are 4 scalar data types in PHP.
1.Integer:
Integers hold only whole numbers including positive and negative numbers,
i.e., numbers without fractional part or decimal point.
Note: Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format.
Ex: to illustrate integer data type
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
?> % Modulus $a % $b
** Exponentiatio $a ** $b
n
2 Assignment operators
Assignment operators are used to assign values to variables.
The basic assignment operator is "=".
The variable on the left side of the operand is updated with the value on the right side.
EX: Operator Name Example
= Assign $a = $b
<?php
$x = 20;
+= Add then Assign $a += $b
$y=10;
-= Subtract then Assign $a -= $b
$x += 100;
$x-=100; *= Multiply then Assign $a *= $b
$y*=10
/= Divide then Assign $a /= $b
echo $y; (quotient)
?>
Logical operators
5.Logical operators are generally used when any action depends on two or more conditions.
The logical operators are used to perform bit-level operations on operands.
<?php
$x = 78; perator Name Example Explanation
and And $a and $b Return TRUE if
$y = 12; both $a and $b
are true
Here we are specifying to shift binary 4 by 3 digits to its left. Hence the resulting output we get
is 32.
8.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.
Syntax:
<?php
/*
this function takes multiple values
separated by comma as input to create
an aray
*/
array();
?>
Advantages of Array
It's very easy to define simple list of related data, rather than creating multiple variables.
It's easy to use and traverse using the foreach loop.
PHP provides built-in functions for sorting array, hence it can be used for sorting information
as well.
In PHP there are 3 types of array:
1. Indexed Array
2. Associative Array
3. Multidimension Array
1. Indexed Array:
An indexed or numeric array stores each array element with a numeric index.
In an indexed array Values are stored and accessed in a linear fashion.
These arrays can store numbers, strings and any object but their index will be represented
by numbers. By default array index starts from zero.
There are two ways to define an indexed array:
1st way:
$language=array("java","c++","C",“python");
2nd way:
$language[0]="java";
$language[1]="C++";
$language[2]="C";
$language[3]=“python";
****Get The Length of an Array - The count() Function
The count() function is used to return the length (the number of elements) of an array:
Viewing Array Structure and Values
You can see the structure that is data type and values of any array by using one of two
statements — var_dump() or print_r().
Ex: To demonstrate var_dump
<?php
// Define array
$cities = array("London", "Paris", "New York");
// Display the cities array
var_dump($cities);
?>
This var_dump() statement gives the following output:
array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8) "New York" }
Ex1 : Todemonstrate indexed array
<?php
$lan = array("Java", "C++", "Phython");
echo "I like " . $lan[0] . ", " . $lan[1] . " and " . $lan[2] . ".";
?>
Output:
I like Java, C++ and Phython.
Ex2: using for loop
<?php
$lan = array("Java", "C++", "Phython");
$arrlength = count($lan);
for($x = 0; $x < $arrlength; $x++) {
echo $lan[$x];
echo "<br>";
}
?>
2. Associative Array:
Associative arrays have a named key as an index, the key can be numeric or text.
We can associate the name with each array element in PHP using => symbol.
Associative arrays are also very useful when retrieving data from the database.
The field names are used as id keys.
Creating Associate array in two ways
1st way:
$salary=array("ram"=>"350000","harika"=>"450000","charan"=>"200000");
2nd way:
$salary["ram"]="350000";
$salary[“Harika"]="450000";
$salary["charan"]="200000";
Ex1: Todemonstrate associative array:
<?php
$salary=array("ram"=>"350000","harika"=>"450000","charan"=>"200000");
echo " ram salary: ".$salary["ram"]."<br/>";
echo " harika salary: ".$salary["harika"]."<br/>";
echo " charansalary: ".$salary["charan"]."<br/>";
?>
ram salary: 350000
harika salary: 450000
charansalary: 200000
Ex2: To demonstrate associative array using foreach loop:
<?php
$salary=array("ram"=>"3500","harika"=>"4500","charan"=>"20000");
// Using for loop
foreach($salary as $sal=>$sal_val)
{
echo "key=" .$sal. ",value=" .$sal_val;
echo "<br>";
}
?>
Output:
key=ram,value=3500
key=harika,value=4500
key=charan,value=20000
3.PHP Multi-dimensional arrays
These are arrays that contain other nested arrays. A multidimensional array is also known as an
array of arrays
It allows you to store tabular data in an array.
The advantage of multidimensional arrays is that they allow us to group related data together.
Traversing Multidimensional Arrays: We can traverse through the multidimensional array using
for and foreach loop.
Ex:
$emp = array
(
array(1,"ram",400000),
array(2,"harika",500000),
array(3,"charan",300000)
);
Ex1: to demonstrate multidimensional array using for loop
<?php
$emp = array
(
array(1,"kiran",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);
<?php
function function_name()
{
// function code statements;
}
?>
Call a function
When a function doesn’t have any parameter, you can call the function by using its name
followed by parentheses like this:
<?php
function_name();
Ex:
<?php
// defining the function
function greetings()
{
echo "Very Happy New Year 2022";
}
greetings();
}
•Built-in functions: PHP provides us with a huge collection of built-in library functions. These
functions are already coded and stored in form of functions.
• To use those we just need to call them as per our requirements like, var_dump, fopen(),
print_r() etc.
•User Defined Functions: we can define our own functions in our program and use those
functions.
•Using this we can create our own packages of code and use it wherever necessary by simply
calling it.
Advantages of User-defined Functions
Code Reusability: functions are defined only once and can be invoked many times.
Less Code: It saves a lot of code because you don't need to write the logic many times.
Easy to understand: PHP functions separate the programming logic. So it is easier to
understand the flow of the application.
PHP Function Arguments
Information can be passed to functions through arguments. An argument is
nothing but a variable.
You can pass any number of arguments to a function but separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-
length argument list.
Syntax: Function with parameters
<?php
function function_name(parameter1, parameter2)
{
// function code statements
}
?>
<?php
function welcome_user($username)
{
echo 'Welcome ' . $username;
}
The welcome_user() function has a parameter $username.
It displays a welcome message to the user by concatenating the Welcome message with
$username.
Parameter passing to Functions
PHP allows us two ways in which an argument can be passed into a function:
•call by value: On passing arguments using pass by value, the value of the argument gets
changed within a function, but the original value outside the function remains unchanged.
•That means a duplicate of the original value is passed as an argument.
•call by reference: On passing arguments as pass by reference, the original value is passed.
Therefore, the original value gets altered.
•In pass by reference we actually pass the address of the value, where it is stored using
ampersand sign(&).
Example :call by value.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Ex: todemonstrate call by reference:
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
PHP Function: Default Argument Value
We can specify a default argument value in function. While calling PHP function if
you don't specify any argument, it will take the default argument.
<?php
// function with default parameter
function def($str, $num=12)
{
echo "$str is $num years old \n";
}
// Calling the function
def("Ram", 15);
// In this call, the default value 12
// will be considered
def("sita");
?>
Return a value
A function can return a value. To return a value from a function, you use the return statement:
return value;
Ex:
<?php
function sum($num1, $num2)
{
$product = $num1 * $num2 ;
return $product;
}
$returnvalue = sum(2, 3);
echo "The product is $returnvalue";
?>
output: The product is 6
Control statements
PHP provides a control statements enabling developers to develop different logic to execute
in different conditions.
A control statement is used in a programming language to control the flow of the program.
Control statements are the statements that are executed randomly and repeatedly.
They are useful to write better and complex programs
controls statement like if statement, if-else statement, break statement, continue statement,
for loop, while loop, do while loop.
Control statements
1.Condition statements
2.Looping statements
3.Jumping statements
1.Condition statements
While writing programs/scripts, there will be scenarios where you want to execute a particular
statement only
if some condition is satisfied. In such situations we use Conditional statements.
In PHP, there are 5 different types of Conditional Statements.
if statements
if...else statements
if...elseif...else statements
nested if
switch statement
if statement
When we want to execute some code when a condition is true, then we use if statement.
Syntax:
if(condition)
{
// code to be executed if 'condition' is true
}
Ex:
<?php
$age = 20;
if($age >= 18)
{
echo "You are allowed to vote";
}
?>
2. if else statement
When we want to execute some code when a condition is true,
and some other code when that condition is false, then we use the if...else .
Syntax:
if(condition) Ex:
{
// code to be executed if 'condition' is true
}
else
{
// code to be executed if 'condition' is false
}
3.The if...else...elseif statement
When we want to execute different code for different set of conditions,
and we have more than 2 possible conditions, then we use if...elseif...else pair.
Syntax:
if(condition1)
{
// code to be executed if 'condition1' is true
}
elseif(condition2)
{
// code to be executed if 'condition2' is true
}
else
{
/* code to be executed if both 'condition1'
and 'condition2' are false */
}
4.nested if Statement
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.
if (condition)
{
//code to be executed if condition is true
if (condition)
{
//code to be executed if condition is true
}
}
5.switch statement is used to execute one statement from multiple condition.
A switch statement is used to perform different actions, based on different conditions.
Syntax
switch(expression)
{ Note:
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
Ex: TO ILLUSTRATE SWITCH STATMENT
<?php
$car = "Jaguar";
switch($car)
{
case "Audi":
echo "Audi is amazing";
break;
case "Mercedes":
echo "Mercedes is mind blowing";
break;
case "Jaguar":
echo "Jaguar is the best";
break;
default:
echo "$car is Ok";
}
Loops:
When you need to execute a block of code or statements several number of times then you
need to use looping concept..
In computer programming, loops are used to to execute a block of code several number of
times . For example, if you want to show a message 100 times, then rather than typing the
same code 100 times, you can use a loop.
Advantage with looping statement
Reduce length of Code
take less memory space.
Burden on the developer is reducing.
Time consuming process to execute the program is reduced.
1.while
2.dowhile
3.for
1.while loop is used to run a block of code repeatedly until a certain condition is true.
When the number of iteration is not fixed then while loop is used.
In while loop first check the condition if condition is true then control goes inside the loop
body otherwise goes outside of the body.
Syntax:
<?php
while(condition)
{
/*
execute this code till the
condition is true
*/
}
?>
2.The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
do..while loop is used where you need to execute code at least once.
<?php
do {
/*
execute this code till the
condition is true
*/
} while(condition)
3.The for loop is used when you know in advance how many times the script should run.
In php for loops execute a block of code specified number of times.
For loop contains 3 parts Initialization, Condition and Increment or Decrements
Syntax:
<?php
for(initialization; condition; increment/decrement)
{
/*
execute this code till the
condition is true
*/
}
?>
4.The foreach loop in PHP is used to access key-value pairs of an array.
This loop only works with arrays and you do not have to initialize any loop counter or set any
condition for exiting from the loop,
everything is done implicitly(internally) by the loop.
Syntax
foreach ($array as $value)
{
code to be executed;
}
Note:
every loop iteration, the value of the current array element is assigned to $value (and the array
pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.
break
The break keyword immediately ends the execution of the loop or switch structure.
The break statement can also be used to jump out of a loop.
The break statement can be used in all types of loops such as while, do-while, for, foreach loop, and
also with switch case.
Syntax
Ex:
<?php
for($i=1;$i<=10;$i++)
{
echo "$i <br/>";
if($i==5)
{
break;
}
}
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
The continue statement can be used with all types of loops such as - for, while, do-while, and foreach
loop
syntax:
continue;
<?php
$list = ["apple", "banana", "cherry"];
foreach ($list as $value) {
if ($value == "banana")
{
continue;
}
echo "I love to eat {$value}fruit";
echo "</br>";
}
Expression:
Almost everything in a PHP script is an expression. Anything that has a value is an expression.
In a typical assignment statement ($x=100), a literal value, a function or operands processed by
operators is an expression, anything that appears to the right of assignment operator (=).
Syntax
Action: By using this attribute we can specify the pagename in which page we can redirect the
form value
Method: we can specify the type of method we are using to send the form values to the server
There are two ways the browser client can send information to the web server.
The GET Method
The POST Method
The GET Method
The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? character.
Ex:http://www.test.com/index.htm?name1=value1&name2=value2
PHP GET Form
Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL)
GET also has limits on the amount of information to send. The limitation is about 2000
characters
Get request is the default form request.
GET may be used for sending non-sensitive data
GET should NEVER be used for sending passwords or other sensitive information!
GET can’t upload the file
The PHP provides The $_GET Super global Variable
The $_GET variable is used to get values from an html form when GET method is used
Syntax
$variable_name = $_GET["field_name"];
Ex to create form with fname and age by using get method
display.html
<html>
<body bgcolor="yellow">
<center> <h1>welcome to home Page </h1></center>
<form action="welcome.php" method="get">
Name: <input type="text" name="fname"></br>
Age: <input type="text" name="age"></br></br>
<input type="submit">
</form>
</body>
</html>
Ex to create php program to read form data by using get method
Welcome.php
<html>
<body bgcolor="pink">
<center> <h1>welcome to Mywebsite</h1></center>
<?php
echo "welcome".$_GET["fname"]."</br>";
echo "your age is". $_GET["age"]; Here notice in url: username and age is visiblein url
?>
</body>
</html>
PHP POST FORM
The POST method transfers information via HTTP headers to server.
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.
Information sent from a form with the POST method is not visible to others or in url.
POST has no limits on the amount of information to send.
POST can upload files to server.
POST is highly secured.
The PHP provides $_POST Super global Variable
The $_POST variable is used to get values from an html form when
POST method is used.
Syntax
$variable_name = $_POST["field_name"];
Ex to create login form by using post method
<html>
<body bgcolor="yellow">
<h1> Login Form </h1>
<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>
</body>
</html>
Ex to create php program to read form data by using post method
login.php
<html>
<body bgcolor="yellow">
<h1> get login data by using post method </h1>
<?php
$name=$_POST["name"];
$password=$_POST["password"];
echo "Welcome: $name, your password is: $password";
?> In URL It is not visible user name and password
</body>
</html>
Reading data from web form controls like text boxes, radio buttons,checkboxes and listbox
Reading data from web form controls like text boxes
What is textbox?
It is html form element in which allows user to enter single line of text in to textbox.
Ex: name, password
The default width of the text field /textbox is 20 characters.
Ex:<input type="text“ name’”t1> defines a text field.
What is Name Attribute of an <input> Element?
The name attribute defines the name of an <input> element. With this attribute, form elements
can send their values to a server when we submit the form-data using a form.
Ex:
Write an html program to design login form by using textbox
<html>
<body bgcolor="yellow">
<center> <h1> Login Page</h1></center>
<form action="welcome1.php" method="post">
Name: <input type="text" name="fname"></br>
Password: <input type="password" name="pass"></br>
<input type="submit“ name=“ok” value=“submit”>
</form>
</body>
</html>
Ex To read data from Textbox/text field
Continue in next slide
Write a php program to read data from textbox/text field
<html>
<body bgcolor="pink">
<center> <h1>Reading data from text box</h1></center>
<?php
echo "welcome".$_GET["fname"]."</br>";
echo "your password is". $_GET[“pass"];
?>
</body>
</html>
Reading Data from check boxes
The checkbox element in HTML allows us to select multiple items from the group of values.
When creating a checkbox form in HTML, the input tag is used and contains
the type and name attributes.
-The type attribute is set to "Checkbox" for Checkboxes.
-The name attribute is the name of each individual checkbox.
If you want to select a checkbox by default, you can use the line checked="checked" for the
given checkbox.
Ex:
<input type="checkbox" name="checkbox_name" value="checkox_value">
Checkboxes are used in questionnaires where a user can select more than one option from a list
of choices.
In order to get the checkbox values, you can use the foreach() method.
Write an html program to design checkbox
<html>
<body bgcolor="green">
<h1> Entering Data with check boxes
</h1>
<form method="post" action="checkbox.php">
<b> Myfavorite Fruit is </b> <br>
<input type="checkbox" name="check1" value="mango"> mango <br>
<input type="checkbox" name="check2" value="apple"> apple <br>
<input type="checkbox" name="check3" value="grapes"> grapes <br>
<input type="submit" value="submit">
</form>
</body>
</html>
Ex1:Write a php program to read data from checkbox
<html>
<body bgcolor="red">
<h1> Reading Data from checkbox </h1>
<?php
$ch1= $_POST['check1'];
$ch2= $_POST['check2'];
$ch3= $_POST['check3'];
if(isset($ch1))
{
echo "your favorite fruit is:". $ch1. "<br>";
}
if(isset($ch2))
{
echo "your favorite fruit is:". $ch2. "<br>";
}
if(isset($ch3))
{
echo "your favorite fruit is:". $ch3. "<br>";
}
?>
</body>
</html>
Output:
Reading Data from checkbox
your favorite fruit is: mango
your favorite fruit is: apple
your favorite fruit is: grapes
Ex 2: write a html program to create checkbox array
<html>
<body bgcolor="yellow">
<h1> Entering Data with check boxes
</h1>
<form action="checkphp.php" method="post">
<input type="checkbox" name="check_list[]" value="C/C++"><label>C/C++</label><br/>
<input type="checkbox" name="check_list[]" value="Java"><label>Java</label><br/>
<input type="checkbox" name="check_list[]" value="PHP"><label>PHP</label><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
Ex2:Write a php program to read data from checkbox array using foreach loop
<?php
echo "Read data from checkbox “. ”<br”;
if(isset($_POST['submit']))
{
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected)
{
echo $selected."</br>";
}
}
?> output:
Read data from checkbox
C/C++
Java
PHP
Radio Button: It is the form element which allows the user to select only one option from the
available choices
When creating a radio button form in HTML, the input tag is used and contains the type, name,
and value attributes.
Example
<?php
session_start();
?>
Storing Session Data: Session data in key-value pairs using the $_SESSION[] superglobal array.
The stored data can be accessed during lifetime of a session.
Below is the PHP code to store a session with two session variables Rollno and Name:
<?php
session_start();
$_SESSION["Rollno"] = "509";
$_SESSION["Name"] = "kiran";
?>
Accessing Session Data:
PHP $_SESSION Global variable
PHP $_SESSION is an associative array that contains all session variables.
It is used to set and get session variable values.
Data stored in sessions can be easily accessed by firstly calling session_start() and then by
passing the corresponding key to the $_SESSION associative array.
<?php
session_start();
?>
Destroying Certain Session Data:
To delete only a certain session data,the unset feature can be used
PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database.
Syntax
mysqli_close($conn);
mysqli_fetch_row:
By using this we can fetch a record from resultset
Executing simple Queries:
1. Creating a Database in Mysql
The Create DataBase statement is used to create a database in Mysql.
The following syntax is used to create a database named "kiran”:
Ex: create database kiran;
The data types that will be used are :
1.VARCHAR: Holds a variable-length string that can contain letters, numbers, and special
characters. The maximum size is specified in parenthesis.
2.INT :The INTEGER data type accepts numeric values with an implied scale of zero. It stores any
integer value between -2147483648 to 2147483647.
The attributes that are used along with data types in this article are:
3.NOT NULL: Each row must contain a value for that column, null values are not allowed.
4.PRIMARY KEY: The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
3.AUTO_INCREMENT :If a column in a table is AUTO_INCREMENT then we do not have to insert
data in that column, it is automatically inserted in the table.
2.Create a Table
The create table statement is used to create a table in MySQL.
Here is a sample query to create a table User, with columns userid, email, password and fullname.
Sytnax:
CREATE TABLE table_name
(
column1 datatype,
column2 datatype,
column3 datatype,
....
);
Ex:// sql query to create table
$sql = "CREATE TABLE User
(
userid INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
fullname VARCHAR(50)
)";
.
3.Insert data into Table
Once a table is created the next step is to enter data into table.
INSERT INTO statement is used to insert new rows in a database table.
TO enter data into table we have to follow certain rules:
If the value to be inserted is string, we must enclose it in quotes.
Numeric value must not be enclosed in quotes.
Note:
You may not need to specify the column(s) name in the SQL query if you are
adding values for all the columns of the table. But make sure the order of the
values is in the same order as the columns in the table.
4.Delete data from Table
The DELETE statement is used to delete records from a database table
// sql query to delete data into table
Syntax: delete from table_name where colume_name=column_value;
Ex:
$sql = "DELETE FROM User WHERE userid=1";
5.Update data in a MY-SQL DataBase
The MySQL UPDATE statement is used to update existing records in a table in a MySQL database.
Note:If you omit the WHERE clause, all records in the table will be updated!
6.Select Data From a MySQL Database :
The SELECT statement is used to select data from one or more tables:
mysqli_close($conn);
?>
write a php program how to connect to database and insert data in to database
<?php
$Hostname =“localhost”;
$Username =“root”;
$Password =‘’”;
$dbname="login";
$conn=mysqli_connect($Hostname, $Username, $Password,$dbname);
if (!$conn)
{
echo "Connection failed";
}
echo "Connected successfully"."<br>";
/ sql to insert data in to table
$sql = "insert into user(empid,firstname, lastname, email)
values(509,'raj', 'kumar', 'rajkumar509@gmail.com')";
if (mysqli_query($conn, $sql))
{
echo "data inserted successfully";
}
else
{
echo "Error creating inserting data: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
write a php program how to connect to database and delete a record from database
<?php
$Hostname =“localhost”;
$Username =“root”;
$Password =“”;
$dbname =“login”;
// Create connection
$conn = mysqli_connect($Hostname,$Username,$Password,$dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql ="delete from user where empid=510";
if (mysqli_query($conn,$sql))
{
echo "Record deleted successfully";
}
else
{
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
write a php program how to connect to database and updata data in database
<?php
$Hostname = "localhost";
$Username = "root";
$Password = "";
$dbname = "kiran";
// Create connection
$conn = mysqli_connect($Hostname, $Username, $Password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "update user set lastname=‘sri’ where empid=562";
if (mysqli_query($conn, $sql))
{
echo "Record updated successfully";
}
else
{
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
write a php progrma how to connect to database and select data from database
<html>
<body bgcolor="yellow">
<?php
$Hostname ="localhost";
$Username ="root";
$Password =‘’”;
$dbname="kiran";
$conn=mysqli_connect($Hostname, $Username, $Password,$dbname);
if (!$conn)
{
echo "Connection failed";
}
echo "Connected successfully"."<br>";
$sql ="select *from user"; // select data from table
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "eid:" .$row["empid"]. "first name:".
$row["firstname"]."lastname:".$row["lastname"]."email:".$row["email"]." <br>";
} }
else
{
echo "0 results";
}
mysqli_close($conn);
?>
</body> </html>
File:
A collection of data or information that has a name, called the filename.
Almost all information stored in a computer must be in a file.
computer programs work with files. This is because files help in storing information
permanently.
Types of files
A binary file is a file that contains information in the same format in which the information is held in
memory i.e. in the binary form
Ex: of binary files
A JPEG image
File Handling:
File handling is needed for any web application. For some tasks to be done file needs to be
processed.
File handling starts with creating a file, reading its content, writing into a file ,Appending data
into an existing file ,deleting a file and finally closing the file.
By using File Handling we can store Data on the Server in PHP
PHP File System provides us some important functions to create file, read file , write file,
append file, delete file and close file.
Ex:
<?php
$file = fopen(“demo.txt”,'w');
?>
Note:
when you open any file you should should get handle,which represents an open file.
From then we can use this handle to work with the file
You can read from it using the various data-reading functions
2.Closing a File:file is closed using fclose() function. Its argument is file which
needs to be closed
• When you open any file and work with it at the end you must close it.
Syntax:
fclose($file)
Ex:
<?php
fclose($file);
?>
3.Reading a file: After file is opened using fopen() the contents of data are read
using fread()
fread(): The PHP fread() function is used to read the content of the file.
The first parameter is the file pointer and the other is the file size in bytes.
Syntax: fread ($file , int $length )
fgets(): The PHP fgets() function is used to read single line from the file.
fgetc(): The PHP fgetc() function is used to read single character from the file.
feof() function can be used to check if the “End-Of-File” (EOF) has been reached.
Ex to read data from the textfile
<?php
echo “Reading data from file”;
$file=fopen("D:\\one.text","r");
while(!feof($file))
{
$text=fread($file,50);
echo $text,"<br>";
}
fclose($file);
echo “file successfully read”;
?>
4: Writing to file: The fwrite() function is used to write to a file. The first parameter
of fwrite() contains the name of the file to write to and the second parameter is the string to be
written.
To use fwrite() function to write content to a file, we first need to open the file in write or
append mode.
• The previous data of the file will be erased if u open file in a ‘w’ mode
• The previous data will not be erased if u open file in a ‘a’ mode
Syntax:
fwrite ( $file ,string $text )
of the file.
Ex to write a content in to a file
<?php
$file = fopen(“D:\\demo.text", "w")
$text = "this is web technologies";
fwrite($file, $text);
fclose($file);
echo “file written successfully”
?>
5.Append to File
• The PHP fwrite() function is used to write and append data into file.
• You can append data into file by using a or a+ mode in fopen() function
Note:
If you use a mode, it will not erase the data of the file. It will write the data at the end
Ex to illustrate append data in to a file.
<?php
$myfile = fopen(“D:\\movies.text, “a+”)
$movie_name = "The Titanic \n";
fwrite($myfile, $movie_name);
$movie_name = " The Mummy \n";
fwrite($myfile, $movie_name);
fclose($myfile);
echo "file written successfully";
?>
6: Deleting a file:
we can delete any file using unlink() function. The unlink() function accepts one argument
only: file name
Syntax : unlink ( string $filename)