0% found this document useful (0 votes)
3 views8 pages

PHP Concept(Introduction)

The document provides an overview of PHP, a server-side scripting language used for web development, covering key concepts such as data type conversion, operators, arrays, string comparison, regular expressions, form processing, database interaction, cookies, and AJAX applications. It includes code examples demonstrating each concept, illustrating how PHP can be used to build dynamic web applications. Additionally, it explains the functionality of AJAX for updating web pages without reloading.

Uploaded by

karthi keyini121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

PHP Concept(Introduction)

The document provides an overview of PHP, a server-side scripting language used for web development, covering key concepts such as data type conversion, operators, arrays, string comparison, regular expressions, form processing, database interaction, cookies, and AJAX applications. It includes code examples demonstrating each concept, illustrating how PHP can be used to build dynamic web applications. Additionally, it explains the functionality of AJAX for updating web pages without reloading.

Uploaded by

karthi keyini121
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Server-Side Programming: PHP

Introduction – Converting between data types – Operators – Arrays – String Comparison –


Regular Expression – Form Processing and Business Logic – Reading from a database – Using
Cookies – Ajax web Application – Ajax example using XMLHttpRequest Object.

1. Introduction to PHP

PHP (Hypertext Preprocessor) is a server-side scripting language primarily used for web
development. PHP code is executed on the server, and the result is sent to the browser.

✅ Example:

<?php
echo "Hello, World!";
?>

🧠 Output: Hello, World!

🔹 2. Converting Between Data Types

PHP is loosely typed, but sometimes you need to convert between types explicitly.

✅ Example:

$number = "10"; // String


$converted = (int)$number; // Convert to integer
echo $converted + 5;

🧠 Output: 15

Use functions like (int), (float), (string) for typecasting.

🔹 3. Operators

PHP supports a wide range of operators:

 Arithmetic: +, -, *, /
 Assignment: =, +=
 Comparison: ==, ===, !=
 Logical: &&, ||, !

✅ Example:

$a = 10;
$b = 5;
echo $a + $b; // Arithmetic
echo $a > $b; // Comparison

🔹 4. Arrays

Arrays store multiple values. PHP has:

 Indexed Arrays
 Associative Arrays
 Multidimensional Arrays

✅ Example:

// Indexed
$colors = ["Red", "Green", "Blue"];
echo $colors[1]; // Green

// Associative
$ages = ["John" => 25, "Jane" => 22];
echo $ages["Jane"]; // 22

🔹 5. String Comparison

Use ==, ===, strcmp() to compare strings.

✅ Example:

$str1 = "hello";
$str2 = "Hello";

if (strcmp($str1, $str2) == 0) {
echo "Equal";
} else {
echo "Not equal";
}

🧠 Output: Not equal (because of case sensitivity)

🔹 6. Regular Expression

Used for pattern matching and validation using functions like preg_match().

✅ Example:
= "[email protected]";
if (preg_match("/^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/", $email)) {
echo "Valid email";
} else {
echo "Invalid email";
}

🔹 7. Form Processing and Business Logic

HTML form collects input, PHP processes it with logic.

✅ Example (HTML):

<form method="post" action="process.php">


Name: <input type="text" name="name">
<input type="submit">
</form>

✅ process.php:

<?php
$name = $_POST['name'];
echo "Hello, " . htmlspecialchars($name);
?>

🔹 8. Reading from a Database (MySQL with mysqli)

✅ Example:

$conn = mysqli_connect("localhost", "root", "", "testdb");


$result = mysqli_query($conn, "SELECT * FROM users");

while($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . "<br>";
}
mysqli_close($conn);

🔹 9. Using Cookies

Cookies store small data on the client's browser.

✅ Set a Cookie:

setcookie("user", "John", time() + 3600); // 1 hour

✅ Read a Cookie:

if(isset($_COOKIE["user"])) {
echo "User is " . $_COOKIE["user"];
}
🔹 10. AJAX Web Application

AJAX (Asynchronous JavaScript and XML) allows updating parts of a page without
reloading.

✅ HTML:

<button onclick="loadData()">Get Data</button>


<div id="result"></div>

✅ JavaScript:

function loadData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);
xhr.onload = function() {
if (this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhr.send();
}

🔹 11. AJAX with XMLHttpRequest (Server File: data.php)

✅ data.php:

<?php
echo "This data was loaded via AJAX!";
?>

🧠 Output (on button click):


This data was loaded via AJAX! appears in the <div>.

1. Introduction to PHP

PHP (Hypertext Preprocessor) is a server-side scripting language widely used for web
development. It is embedded within HTML and executes on the server.

Example:

<?php
echo "Hello, World!";
?>
Explanation: This script uses echo to output the string "Hello, World!". The <?php ... ?>
tags denote PHP code.

2. Converting Between Data Types

PHP is loosely typed, but conversions can be done explicitly.

Example:

$number = "10";
$converted = (int)$number;
echo $converted + 5; // Outputs 15

Explanation: The string "10" is typecast to an integer using (int), and then added to 5. The
result is 15.

3. Operators in PHP

Types of operators:

 Arithmetic: +, -, *, /
 Assignment: =, +=, etc.
 Comparison: ==, ===, !=
 Logical: &&, ||, !

Example:

$a = 10;
$b = 5;
echo $a + $b; // Outputs 15
echo $a > $b; // Outputs 1 (true)

Explanation: The first line adds two integers. The second line compares them and returns
true (represented as 1 in PHP).

4. Arrays in PHP

 Indexed Arrays
 Associative Arrays
 Multidimensional Arrays

Example:

$colors = ["Red", "Green", "Blue"];


echo $colors[1]; // Green
$ages = ["John" => 25, "Jane" => 22];
echo $ages["Jane"]; // 22

Explanation: $colors is an indexed array where elements are accessed using numeric
indices. $ages is an associative array where elements are accessed using named keys.

5. String Comparison

Use ==, ===, or strcmp().

Example:

$str1 = "hello";
$str2 = "Hello";
echo strcmp($str1, $str2); // Outputs a non-zero value (case-sensitive)

Explanation: strcmp() compares two strings. It returns 0 if they are equal, a positive
number if $str1 is greater, or a negative if smaller. Case matters here.

6. Regular Expressions

Used for pattern matching and input validation.

Example:

$email = "[email protected]";
if (preg_match("/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/", $email)) {
echo "Valid email";
} else {
echo "Invalid email";
}

Explanation: The preg_match function checks if $email matches the given regular
expression pattern for a basic email format.

7. Form Processing and Business Logic

HTML Form:

<form method="post" action="process.php">


Name: <input type="text" name="name">
<input type="submit">
</form>

process.php:
<?php
$name = $_POST['name'];
echo "Hello, " . htmlspecialchars($name);
?>

Explanation: The form sends data via POST to process.php. The PHP script retrieves the
name using $_POST['name'] and prints a greeting, using htmlspecialchars() to prevent
XSS attacks.

8. Reading from a Database

Example:

$conn = mysqli_connect("localhost", "root", "", "testdb");


$result = mysqli_query($conn, "SELECT * FROM users");

while($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . "<br>";
}
mysqli_close($conn);

Explanation:

 mysqli_connect() connects to the MySQL database.


 mysqli_query() runs an SQL query.
 mysqli_fetch_assoc() retrieves each row as an associative array.
 The usernames are printed with a line break.
 mysqli_close() closes the connection.

9. Using Cookies

Set a Cookie:

setcookie("user", "John", time() + 3600);

Read a Cookie:

if(isset($_COOKIE["user"])) {
echo "User is " . $_COOKIE["user"];
}

Explanation: setcookie() sets a cookie named "user" with value "John" that expires in 1
hour. $_COOKIE is used to access the stored cookie value.

10. AJAX Web Application


Allows dynamic updates without reloading the page.

HTML:

<button onclick="loadData()">Get Data</button>


<div id="result"></div>

JavaScript:

function loadData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);
xhr.onload = function() {
if (this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhr.send();
}

Explanation: XMLHttpRequest is used to fetch data asynchronously from data.php. On


success, the returned data is displayed in the <div> with id result.

11. AJAX Example using XMLHttpRequest

data.php:

<?php
echo "This data was loaded via AJAX!";
?>

Explanation: This PHP file simply returns a string. When requested via AJAX, the string is
inserted into the web page without reloading.

You might also like