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

PHP Basic

Uploaded by

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

PHP Basic

Uploaded by

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

PHP Basic

• PHP is an acronym for "PHP: Hypertext Preprocessor"


• PHP is a widely-used, open-source scripting language
• PHP scripts are executed on the server and the result is returned to the browser as
plain HTML
• PHP is free to download and use
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP files have extension ".php"
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database and supports a wide range of
databases (Oracle, Microsoft SQL Server, MySQL, PostgreSQL, Sybase, and
Informix.)
• PHP can be used to control user-access
• PHP can encrypt data
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)

Syntax
<?php
PHP code goes here
?>

Example://first.php
<?php
# Here echo command is used to print
echo "Hello, world!";
?>

<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are not case-sensitive.

<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Note: However; all variable names are case-sensitive!

<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>

comments
<?php
// Output "Hello VitBhopal"
echo "Hello VitBhopal";
?>

<?php
echo "Hello VitBhopal";
/* It will print the
message " Hello VitBhopal " */
?>

PHP supports the following data types:


• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource

<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
var_dump($x);
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello";
print "Hello";
echo "Multiple ","argument ","string!";
print "Multiple ","argument ","string!";
?>
</body>
</html>

String
<!DOCTYPE html>
<html>
<body>
<?php
$str1 = 'Welcome to VIT Bhopal University';
$str2 = "Welcome SAM";
echo $str1;
echo $str2;
?>
</body>
</html>

PHP Variables
A variable can have a short name (like $x and $y) or a more descriptive name
($age, $carname, $total_volume).
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
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different variables)
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "University";
echo " VIT Bhopal $txt!";
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
$txt = " University ";
echo " VIT Bhopal " . $txt . "!";
?>
</body>
</html>

Control and Loop Statements

<!DOCTYPE html>
<html>
<body>
<?php
if (5 > 3) {
echo "Have a good day!";
}
?>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<?php
$tot=88;
if ($tot > 50) {
echo "pass!";
} else {
echo "Fail";
}
?>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<?php
$t = 10;
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
/body>
</html>

<!DOCTYPE html>
<html>
<body>
<?php
$i = 1;
while ($i < 6) {
print $i;
$i++;
}
?>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<?php
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x <= 10; $x++)
echo "The number is: $x <br>";
?>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";
}
?>
</body>
</html>

<?php
// Declare an array
$arr = array("green", "blue", "pink", "white");
// Loop through the array elements
foreach ($arr as $element) {
echo "$element ";
}
?>

PHP Arrays
An array is a special variable that can hold many values under a single name, and you can
access the values by referring to an index number or name. To store multiple elements of
similar or different data types under a single variable thereby saving us the effort of creating a
different variable for every data.

Types of Array in PHP


• Indexed or Numeric Arrays: An array with a numeric index where values are stored
linearly.
• Associative Arrays: An array with a string index where instead of linear storage, each
value can be assigned a specific key.
• Multidimensional Arrays: An array that contains a single or multiple arrays within it
and can be accessed via multiple indices.
PHP Indexed Arrays
In indexed arrays each item has an index number.

<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");

for($n = 0; $n < 3; $n++){


echo $cars[$n]." ";
}

foreach ($cars as $x) {


echo "$x <br>";
}

$name = array("SAM", "John", 111);

for($n = 0; $n < 3; $n++){


echo $name[$n]." ";
}
?>
</body>
</html>

PHP Associative Arrays


These types of arrays are similar to the indexed arrays but instead of linear storage, every value can be
assigned with a user-defined key of string type.Associative arrays are arrays that use named keys that
you assign to them.

<!DOCTYPE html>
<html>
<body>
<?php
$name = array("1001"=>"Zara", "1002"=>"Rani",
"1003"=>"Sara",
"1004"=>"Ravina");
var_dump($name);
foreach ($name as $x => $y) {
echo "$x: $y <br>";
}

?>
</body>
</html>

PHP - Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.PHP supports multidimensional
arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep
are hard to manage for most people.
<!DOCTYPE html>
<html>
<body>

<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";


echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>

</body>
</html>

<?php
// Defining a multidimensional array
$favorites = array(
"Dave Punk" => array(
"mob" => "5689741523",
"email" => "[email protected]",
),
"Smith John" => array(
"mob" => "2584369721",
"email" => "[email protected]",
),
"John Flinch" => array(
"mob" => "9875147536",
"email" => "[email protected]",
)
);

// Using for and foreach in nested form


$keys = array_keys($favorites);
for($i = 0; $i < count($favorites); $i++) {
echo "$keys[$i]<br>";

foreach($favorites[$keys[$i]] as $key => $value) {


echo $key . " : " . $value . "<br>";
}
echo "\n";
}

?>
PHP Functions
A function is a block of code written in a program to perform some specific task.
PHP provides us with two major types of functions:

• Built-in functions : PHP provides us with 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 requirement like, var_dump, fopen(),
print_r(), gettype() and so on.
• User Defined Functions : Apart from the built-in functions, PHP allows us to create
our own customised functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by
simply calling it.

Syntax:

function function_name(){
executable code;
}

<?php
function func1()
{
echo "Welcome to VIT Bhopal";
}
// Calling the function
func1();
?>

Function Parameters or Arguments


Information can be passed to functions through arguments. An argument is just like a
variable. Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.

Syntax:
function function_name($first_parameter, $second_parameter) {
executable code;
}

<?php
// function along with three parameters
function prod3($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}
// Calling the function
// Passing three arguments
prod3(2, 3, 5);
?>

Setting Default Values for Function parameter

PHP allows us to set default argument values for function parameters. If we do not pass any
argument for a parameter with default value then PHP will use the default set value for this
parameter in the function call.
Example:
<?php

// function along with three parameters


function prod3($num1, $num2, $num3=5)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}

// Calling the function


// Passing 2 arguments
prod3(2, 4);

?>

PHP Functions - Returning values


To let a function return a value, use the return statement:
<?php

// function along with three parameters


function prod3($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;

return $product; //returning the product


}

// storing the returned value


$retValue = prod3(2, 4, 5);
echo "The product is $retValue";

?>

Parameter passing to Functions


PHP allows us two ways in which an argument can be passed into a function:

• Pass 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.
• Pass 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(&).
<?php

// pass by value
function val($num) {
$num += 2;
return $num;
}

// pass by reference
function ref(&$num) {
$num += 10;
return $num;
}
$n = 10;
val($n);
echo "The original value is still $n \n";
ref($n);
echo "The original value changes to $n";
?>

PHP Form
HTML forms are used to send the user information to the server and returns the result back to
the browser.

Phpform.html
<!DOCTYPE HTML>
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
welcome.php
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>

Php form validation


<html>
<body>

<form action="form_handler.php" method="POST">

Name: <input type="text" name="name"> <br/>


Email: <input type="text" name="email"> <br/>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

form_handler.php
<?php
$name = $_POST["name"];
$email = $_POST["email"];
if(empty($name))
{
echo "Name is required";
}
else echo "name...: " . $name . "<br>";

if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Email value invalid";
}else echo "email id is...: " . $email;
?>

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<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>
File handling

File handling in PHP is similar as file handling is done by using any programming language
like C. PHP has many functions to work with normal files. Those functions are:

1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen() contains
name of the file which is to be opened and second parameter tells about mode in which file
needs to be opened, e.g.,

<?php
$file = fopen(“demo.txt”,'w');
?>
Files can be opened in any of the following modes :

“w” – Opens a file for write only. If file not exist then new file is created and if file already
exists then contents of file is erased.
“r” – File is opened for read only.
“a” – File is opened for write only. File pointer points to end of file. Existing data in file is
preserved.
“w+” – Opens file for read and write. If file not exist then new file is created and if file
already exists then contents of file is erased.
“r+” – File is opened for read/write.
“a+” – File is opened for write/read. File pointer points to end of file. Existing data in file is
preserved. If file is not there then new file is created.
“x” – New file is created for write only.

2) fread() –– After file is opened using fopen() the contents of data are read using fread(). It
takes two arguments. One is file pointer and another is file size in bytes, e.g.,

<?php
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
$filedata = fread( $file, $size );
?>

3) fwrite() – New file can be created or text can be appended to an existing file using fwrite()
function. Arguments for fwrite() function are file pointer and text that is to written to file. It
can contain optional third argument where length of text to written is specified, e.g.,

<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>

4) fclose() – file is closed using fclose() function. Its argument is file which needs to be
closed, e.g.,

<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>
Example1:

<?php
$myfile = fopen('test.txt', 'r') ;
if ($myfile)
// Read the contents of the file
$contents = fread($myfile, filesize('test.txt'));
fclose($myfile);
// Print the contents of the file
echo $contents;
?>

Example2:

<?php
$myfile = fopen("newfile.txt", "w") ;
$txt = "java programming language\n";
fwrite($myfile, $txt);
$txt = "python programming language\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

Example3:

<?php
$myfile = fopen("test.txt", "r");
//echo fread($myfile,filesize("test.txt"));
//$myfile = fopen("test.txt", "r");
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";// echo fgetc($myfile);
}
fclose($myfile);
?>

Example 4:
<?php
$myfile = fopen("test.txt", "r");
echo fread($myfile,filesize("test.txt"));
fclose($myfile);
?>
Example 5:

<?php
echo readfile("test.txt");
?>

Example 6:

<?php
$myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
$txt = "Internet programming";
fwrite($myfile, $txt);
fclose($myfile);
?>
Uploading File
HTML source code for the HTML form for uploading the file to the server. In the
HTML <form> tag, we are using “enctype=’multipart/form-data” which is an encoding type
that allows files to be sent through a POST method. Without this encoding, the files cannot be
sent through the POST method. We must use this enctype if you want to allow users to upload
a file through a form.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<h2>Upload a File</h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedFile" required>
<br><br>
<input type="submit" name="submit" value="Upload File">
</form>
</body>
</html>

<?php
if (isset($_POST['submit'])) {
// Directory where the file will be uploaded
$uploadDir = "uploads/";

// Ensure the uploads directory exists


if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}

// File details
$fileName = basename($_FILES["uploadedFile"]["name"]);
$fileType = $_FILES["uploadedFile"]["type"];
$fileSize = $_FILES["uploadedFile"]["size"];
$fileTmpName = $_FILES["uploadedFile"]["tmp_name"];
$uploadFilePath = $uploadDir . $fileName;

// Check if the file is successfully uploaded


if (move_uploaded_file($fileTmpName, $uploadFilePath)) {
echo "<h3>File Uploaded Successfully!</h3>";
echo "<p><strong>File Name:</strong> " . htmlspecialchars($fileName) . "</p>";
echo "<p><strong>File Type:</strong> " . htmlspecialchars($fileType) . "</p>";
echo "<p><strong>File Size:</strong> " . ($fileSize / 1024) . " KB</p>";
echo "<p><strong>File Path:</strong> " . htmlspecialchars($uploadFilePath) . "</p>";
} else {
echo "<h3>File Upload Failed!</h3>";
}
}
?>

The php script first checks if the form was submitted.The uploaded file details are extracted
using the $_FILES superglobal array.The script checks if the uploads directory exists, and if
not, it creates it.The move_uploaded_file() function is used to move the uploaded file from its
temporary location to the desired directory.If the upload is successful, the file details are
displayed; otherwise, an error message is shown.

Date and Time


Date and time are some of the most frequently used operations in PHP while executing SQL
queries or designing a website etc. PHP serves us with predefined functions for these tasks.
Some of the predefined functions in PHP for date and time are discussed below.
PHP date() Function: The PHP date() function converts timestamp to a more readable date and
time format.

Syntax:
date(format, timestamp)

Explanation:
• The format parameter in the date() function specifies the format of returned date and
time.
• The timestamp is an optional parameter, if it is not included then the current date and
time will be used.
Date-related formatting characters that are commonly used in the format string:
• d: Represents day of the month; two digits with leading zeros (01 or 31).
• D: Represents day of the week in the text as an abbreviation (Mon to Sun).
• m: Represents month in numbers with leading zeros (01 or 12).
• M: Represents month in text, abbreviated (Jan to Dec).
• y: Represents year in two digits (08 or 14).
• Y: Represents year in four digits (2008 or 2014).
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.),
slashes (/), or spaces to add additional visual formatting.

PHP time() Function: The time() function is used to get the current time as a Unix timestamp
(the number of seconds since the beginning of the Unix epoch: January 1, 1970, 00:00:00
GMT).
The following characters can be used to format the time string:
• h: Represents hour in 12-hour format with leading zeros (01 to 12).
• H: Represents hour in 24-hour format with leading zeros (00 to 23).
• i: Represents minutes with leading zeros (00 to 59).
• s: Represents seconds with leading zeros (00 to 59).
• a: Represents lowercase antemeridian and post meridian (am or pm).
• A: Represents uppercase antemeridian and post meridian (AM or PM).
Example1
<!DOCTYPE html>
<html>
<body>

<?php
echo "The time is " . date("h:i:sa");
?>

</body>
</html>

Example2

<?php
echo date("h:i:s") . "\n";
echo date("M,d,Y h:i:s A") . "\n";
echo date("h:i a");
?>
//Date and Time
<!DOCTYPE html>
<html>
<body>
// date(format, timestamp)
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("d/m/Y") . "<br>";
$today = date("d/m/Y");
echo "Today is " . date("l");
?>

</body>
</html>

<!DOCTYPE html>
<html>
<body>
<?php
$timestamp = time();
echo(date("F d, Y h:i:s A", $timestamp));
?>
</body>
</html>

Creating a MySQL Table Using MySQLi


Connecting to MySQL database using PHP
There are 3 ways in which we can connect to MySQl from PHP as listed above and described below:
• Using MySQLi object-oriented procedure: We can use the MySQLi object-oriented
procedure to establish a connection to MySQL database from a PHP script.
Example1(connection to MySQL database)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Creating connection
$conn = new mysqli($servername, $username, $password);

// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
//$conn->close();

?>
Example2(creating and connection to MySQL database)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Creating a connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Creating a database named newDB
$sql = "CREATE DATABASE newDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully with the name newDB";
} else {
echo "Error creating database: " . $conn->error;
}
// closing connection
$conn->close();
?>

Create a MySQL Table Using MySQLi


<?php
$servername = "localhost";
$username = "root";
$password = "lochan239";
$dbname = "msdatabase";

// checking connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql code to create table


$sql = "CREATE TABLE employees(
id INT(2) PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50)
)";

if ($conn->query($sql) === TRUE) {


echo "Table employees created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

Insert Data Into MySQL Using MySQLi


<?php
$mysqli = new mysqli("localhost", "root", "lochan239", "msdatabase");

if ($mysqli == false) {
die("ERROR: Could not connect. ".$mysqli->connect_error);
}

$sql = "INSERT INTO employees (id,firstname, lastname, email)


VALUES (101,'John', 'smith', '[email protected]')";

if ($mysqli->query($sql) == true)
{
echo "Records inserted successfully.";
}
else
{
echo "ERROR: Could not able to execute $sql. "
.$mysqli->error;
}

// Close connection
$mysqli->close();
?>
Insert Multiple Records Into MySQL Using MySQLi

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";

if ($conn->multi_query($sql) === TRUE) {


echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Select Data With MySQLi

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydatabase";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM employees";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

Create HTML form for connecting to database


<!DOCTYPE html>
<html >
<head>
<title>Contact Form - PHP/MySQL Demo Code</title>
</head>
<body>
<form name="frmContact" method="post" action="contact.php">
<p>
<label for="ID">EMPid </label>
<input type="text" name="Empid" id="Empid">
</p>
<p>
<label for="fName">FirstName </label>
<input type="text" name="fName" id="fName">
</p>
<p>
<label for="lName">LastName </label>
<input type="text" name="lName" id="lName">
</p>

<p>
<label for="email">Email</label>
<input type="text" name="Email" id="Email">
</p>
<p>&nbsp;</p>
<p>
<input type="submit" name="Submit" id="Submit" value="Submit">
</p>
</form>
</fieldset>
</body>
</html>
//php code to insert data in mysql USING FORM DATA
<?php
// database connection code
$conn = new mysqli('localhost', 'root', 'lochan239','msdatabase');
// get the post records
$id = $_POST['Empid'];
$txtfName = $_POST['fName'];
$txtlName = $_POST['lName'];
$txtEmail = $_POST['Email'];
// database insert SQL code
echo $id;
echo $txtfName;
echo $txtlName;
echo $txtEmail;
$sql = "INSERT INTO employees (id, firstname, lastname, email) VALUES
('$id','$txtfName','$txtlName', '$txtEmail')";
// insert in database
$rs = mysqli_query($conn, $sql);
if($rs)
{
echo "Records Inserted";
}
?>

Cookies
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
Create Cookies With PHP
A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure);

Argument What is it for?


Used to specify the name of the cookie. It is a mandatory argument. Name of the
name
cookie must be a string.
Used to store any value in the cookie. It is generally saved as a pair with name. For
value
example, name is userid and value is 7007, the userid for any user.
Used to set the expiration time for a cookie. if you do not provide any value, the
expire cookie will be treated as a session cookie and will expire when the browser is
closed.
Used to set a web URL in the cookie. If set, the cookie will be accessible only from
path
that URL. To make a cookie accessible through a domain, set '/' as cookie path.
The domain of your web application. It can be used to limit access of cookie for
domain sub-domains. For example, if you set the domain value as wwww.vitbhopal.com,
then the cookie will be inaccessible from blog.vitbhopal.com
If you set this to 1, then the cookie will be available and sent only over HTTPS
secure
connection.

Create/Retrieve a Cookie

<?php
$cookie_name = "vitbhopal";
$cookie_value = "vitb";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>

ACCESSING COOKIES WITH PHP


PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE
or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set
in
above example.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body>
</html>
We can use isset() function to check if a cookie is set or not.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
DELETING COOKIE WITH PHP
Officially, to delete a cookie you should call setcookie() with the name argument only
but
this does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired −
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>

Session
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["name"] = "session";
$_SESSION["number"] = "1";
echo "Session variables are set." . "<br>";
echo $_SESSION["name"] . $_SESSION["number"];
?>
</body>
</html>

E-mail in PHP
<?php
// Recipient's email address
$to = "[email protected]";

// Email subject
$subject = "Test Email from PHP";

// Email message
$message = "Hello,\n\nThis is a test email sent from a PHP script.";

// Additional headers
$headers = "From: [email protected]" . "\r\n" .
"Reply-To: [email protected]" . "\r\n" .
"X-Mailer: PHP/" . phpversion();

// Send email
if(mail($to, $subject, $message, $headers)) {
echo "Email sent successfully to $to";
} else {
echo "Failed to send email.";
}
?>

1. Recipient:
$to is the recipient's email address.
2. Subject:
$subject is the subject of the email.
3. Message:
$message contains the body of the email. You can include newlines using \n.
4. Headers:
$headers define additional headers, such as From, Reply-To, and X-Mailer.
The From header specifies the sender’s email address.
The Reply-To header specifies the email address for replies.
X-Mailer is optional and includes information about the software used to send
the email.
5. Sending the Email:
The mail() function is used to send the email. If the email is sent successfully,
it returns true; otherwise, it returns false.
Important Notes:
• SMTP Server: Ensure that your server is configured with a working SMTP server to
send emails. Without this configuration, the mail() function may not work as
expected.
• Headers Injection: Be cautious of header injection attacks if you are accepting email
inputs from users. Validate and sanitize inputs accordingly.
• Error Handling: In a production environment, you might want to handle errors more
gracefully, perhaps logging failed attempts.
Testing on Localhost:
• If you’re testing on localhost, you’ll need a mail server like sendmail on Linux or a
tool like MailHog to capture outgoing emails.
• Alternatively, you can use third-party services like Gmail's SMTP server to send
emails, but this requires additional configuration.

PHP and XML

o read and update, create and manipulate an XML document, you will need an XML parser.
In PHP there are two major types of XML parsers:
• Tree-Based Parsers
• Event-Based Parsers
Tree-Based Parsers
Tree-based parsers holds the entire document in Memory and transforms the XML document
into a Tree structure. It analyzes the whole document, and provides access to the Tree
elements (DOM).
This type of parser is a better option for smaller XML documents, but not for large XML
document as it causes major performance issues.
Example of tree-based parsers:
• SimpleXML
• DOM

Event-Based Parsers
Event-based parsers do not hold the entire document in Memory, instead, they read in one
node at a time and allow you to interact with in real time. Once you move onto the next node,
the old one is thrown away.
This type of parser is well suited for large XML documents. It parses faster and consumes
less memory.
Example of event-based parsers:
• XMLReader
• XML Expat Parser

SimpleXML is a PHP extension that allows us to easily manipulate and get XML data.

The SimpleXML Parser


SimpleXML is a tree-based parser.
SimpleXML provides an easy way of getting an element's name, attributes and textual
content if you know the XML document's structure or layout.
SimpleXML turns an XML document into a data structure you can iterate through like a
collection of arrays and objects.
Compared to DOM or the Expat parser, SimpleXML takes a fewer lines of code to read text
data from an element.

PHP SimpleXML - Read From String


The PHP simplexml_load_string() function is used to read XML data from a string.
Assume we have a variable that contains XML data, like this:
<!DOCTYPE html>
<html>
<body>
<?php
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";
$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
print_r($xml);
?>
</body>
</html>

PHP and AJAX.

PHP powered web applications often make use of AJAX, together they are useful to create
dynamic and interactive web applications. AJAX stands for Asynchronous Javascript and
XML. It allows webpages to be updated asynchronously without reloading the entire page.
To use AJAX with PHP, you will need to use the XMLHttpRequest object in JavaScript to send
requests to the PHP server. The PHP server will then process the request and return a response,
typically in the form of JSON or XML. The JavaScript code can then parse the response and
update the web page accordingly.
The XMLHttpRequest object in JavaScript is a browser-based API that allows developers to
make HTTP requests to a server without reloading the page. This is the foundation of AJAX
programming, which allows for dynamic and interactive web applications.
The XMLHttpRequest object can be used to −
• Retrieve data from a server, such as JSON, XML, or HTML.
• Send data to a server, such as form data or file uploads.
• Update a web page without reloading it.
• Create chat applications and other interactive features.
To use the XMLHttpRequest object, you first need to create a new instance of it. Then, you
can use the open() method to specify the HTTP method and request URL. Next, you can set
any request headers, if needed. Finally, you can send the request using the send() method.

AJAX PHP Example


The following example will demonstrate how a web page can communicate with a web server
while a user type characters in an input field:

<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form action="">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
Code explanation:
First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint
placeholder and exit the function.
However, if the input field is not empty, do the following:
• Create an XMLHttpRequest object
• Create the function to be executed when the server response is ready
• Send the request off to a PHP file (gethint.php) on the server
• Notice that q parameter is added to the url (gethint.php?q=" + str)
• And the str variable holds the content of the input field

gethint.php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";

// get the q parameter from URL


$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""


if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}

// Output "no suggestion" if no hint was found or output correct values


echo $hint === "" ? "no suggestion" : $hint;

You might also like