Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

A Simple Webpage Using PHP

The document provides examples of various PHP programming concepts like variables, data types, operators, conditional statements, loops, arrays, functions, file handling, database connectivity etc. It includes 21 code snippets with explanations demonstrating PHP syntax and features like: 1. Defining and echoing a variable. 2. If-else conditional statement. 3. Nested if-elseif-else statement to find largest number. 4. Switch statement. 5. While, do-while and for loops. 6. Foreach loop to iterate through an array. 7. Sorting and displaying numerical and associative arrays. 8. Creating sessions and cookies. 9. File handling operations like opening,

Uploaded by

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

A Simple Webpage Using PHP

The document provides examples of various PHP programming concepts like variables, data types, operators, conditional statements, loops, arrays, functions, file handling, database connectivity etc. It includes 21 code snippets with explanations demonstrating PHP syntax and features like: 1. Defining and echoing a variable. 2. If-else conditional statement. 3. Nested if-elseif-else statement to find largest number. 4. Switch statement. 5. While, do-while and for loops. 6. Foreach loop to iterate through an array. 7. Sorting and displaying numerical and associative arrays. 8. Creating sessions and cookies. 9. File handling operations like opening,

Uploaded by

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

1.

A SIMPLE WEBPAGE USING PHP

<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #2C6BF5; /* light gray background */
}
</style>
<title>My PHP Webpage</title> </head>
<body>
<?php
// Define a variable
$message = "Hello, world!"; // Output the variable
echo "<h1>" . $message . "</h1>"; ?>
<p>This is a simple webpage using PHP.</p> </body>
</html>
OUTPUT :
2. IF – ELSE STATEMENTS IN PHP

<?php
// Use an if else statement to check if x is less than 10
$x = 10;
if ($x < 10) {
echo "x is less than 10.<br>";
} else {
echo "x is not less than 10.<br>";
}
?>
OUTPUT :

x is not less than 10.


3. NESTED STATEMENTS IN PHP

<?php
// Use if elseif else statement to check largest of two number.
$x=20;
$y =15; $z=22; if($x>$y && $x>$z){
echo " $x is largest";
}
elseif($y>$x && $y>$z){
echo " $y is largest";
} else{ echo " $z is largest";
}
?>
OUTPUT :

22 is largest
4. SWITCH STATEMENT IN PHP

<?php
// Use a switch statement to check the value of x
$x = 5;
switch ($x) {
case 1:
echo "x is equal to 1.<br>";break;
case 2:
echo "x is equal to 2.<br>";
break;
case 3:
echo "x is equal to 3.<br>";
break;
default:
echo "x is not equal to 1, 2, or 3.<br>"; break;
} ?>
OUTPUT:

X is not equal to 1, 2, or 3.
5. WHILE LOOP STATEMENT IN PHP

<?php
// Loop through numbers 1 to 10 using a while loop
echo "Using a while loop:<br>";
$i = 1;
while ($i <= 10) {
echo $i . " ";
$i++;
}
echo "<br>";
?>
OUTPUT:

Using a while loop


1 2 3 4 5 6 7 8 9 10
6. DO - WHILE LOOP STATEMENT IN PHP

<?php
// Use a do-while loop to print the numbers from 1 to 5
echo "Using a do-while loop:<br>";
$x = 1;
do {
echo $x . " ";
$x++;
} while ($x <= 5);
echo "<br>";
?>
OUTPUT:

Using a do-while loop:


12345
7. FOR LOOP STATEMENT IN PHP

<?php
// Loop through numbers 1 to 10 using a for loop
echo "Using a for loop:<br>";
for ($i = 1; $i <= 10; $i++) {
echo $i . " ";
}
?>
OUTPUT:

Using a for loop


1 2 3 4 5 6 7 8 9 10
8. FOR EACH LOOP STATEMENT IN PHP

<?php
// Loop through an array of fruits using a foreach loop
echo "Using a foreach loop:<br>";
$fruits = array("apple", "banana", "orange", "kiwi");
foreach ($fruits as $fruit) {
echo $fruit . " "; }
echo "<br>";
?>
OUTPUT:

Using a for each loop:


apple banana orange kiwi
9. DISPLAY A NUMERICAL ARRAY

<?php
// create an indexed array
$name_one = array("zack", "anthony", "ram", "salim", "raghav");
// Accessing the elements directly
echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n ";
?>
OUTPUT:

Accessing the 1st array elements directly: ram zack raghav.


10. DISPLAY AN ASSOCIATIVE ARRAY

<?php
// One way to create an associative array
$name_two = array("zack"=>"zara", "anthony"=>"any","ram"=>"rani",
"salim"=>"sara","raghav"=>"ravina");
// Accessing the elements directly
echo "Accessing the elements directly:\n";
echo $name_two["zack"], "\n";
echo $name_two["salim"], "\n <br>";
?>
OUTPUT:

Accessing the elements directly: zara sara


11. DISPLAY MULTI DIMENSIONAL ARRAY

<?php
// Defining a multidimensional array
$favorites = array(
array(
"name" => "Dave Punk",
"mob" => "5689741523",
"email" => "davepunk@gmail.com, <br>"
),
array(
"name" => "Monty Smith",
"mob" => "2584369721",
"email" => "montysmith@gmail.com, <br>"
),
array("name" => "John Flinch",
"mob" => "9875147536",
"email" => "johnflinch@gmail.com, <br>"
),
);
// Accessing elements
echo "Dave Punk email-id is: " . $favorites[0]["email"], "\n";
echo "John Flinch mobile number is: " . $favorites[2]["mob"],"\n";
?>
OUTPUT:

Dave Punk email-id is: davepunk@gmail.com,


John Flinch mobile number is: 9875147536
12. TO SORT AN ARRAY ELEMENT.

<?php
$numbers = readline("Enter the numbers:");
$numbers_array = explode(",", $numbers);
$numbers_array = array_map('trim', $numbers array);
$numbers_array = array_map('intval',
$numbers_array); sort($numbers_array);
echo "sorted numbers:";
echo implode(",", $numbers_array);
?>
Output:
Enter the numbers : 5,6,7,3,2
sorted numbers : 2,3,5,6,7
13. CREATION OF SESSION

<?php
// Start the session
session_start();
// Set session variables
$_SESSION['username'] = 'JohnDoe';
$_SESSION['email'] = 'johndoe@example.com';
?>
<!DOCTYPE html>
<html>
<head>
<title>Session Test</title>
</head>
<body>
<h1>Welcome, <?php echo $_SESSION['username']; ?>!</h1>
<p>Your email address is: <?php echo $_SESSION['email']; ?></p>
</body>
</html>
OUTPUT:

Welcome, JohnDoe!
Your email address is: johndoe@example.com
14. CREATION OF COOKIES

<?php
// Set the cookie
setcookie("username", "JohnDoe", time() + 86400); // expires after 1 day ?>
<!DOCTYPE html>
<html>
<head>
<title>Cookie Test</title>
</head>
<body>
<?php
// Check if the cookie is set
if(isset($_COOKIE['username'])) {
echo "Welcome back, " . $_COOKIE['username'] . "!"; } else {
echo "You are a new visitor!"; }
?> </body> </html>
OUTPUT:

You are a new visitor!


15. PHP FILE MANIPULATION

<?php
// Open a file for writing
$myfile = fopen("example.txt", "w") or die("Unable to open file!");
// Write some text to the file
$txt = "Hello, world!";
fwrite($myfile, $txt);
// Close the file
fclose($myfile);
// Open the file for reading
$myfile = fopen("example.txt", "r") or die("Unable to open file!");
// Read the contents of the file
echo fread($myfile,filesize("example.txt"));
// Close the file fclose($myfile);
// Delete the file unlink("example.txt");
?>
OUTPUT:
Hello, world!
16. SIMPLE APPLICATION USING POST METHOD.

1. postexample.html

<html>

<head>

<title>Post Example</title>

</head>

<body>

<h1>Post Example</h1>

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

<label for="name">Name:</label>

<input type="text" id="name" name="name"><br>

<input type="submit" name="submit" value="Submit">

</form>

</body>

</html>

2. post.php

<?php

if($_SERVER['REQUEST_METHOD']=='POST')

$name=$_POST['name'];

echo"<p>hello,$name!</p>";

?>
Output:

Hello, john!
17. SIMPLE APPLICATION USING GET METHOD.

1. getexample.html

<html>

<head>

<title>Get Example</title>

</head>

<body>

<h1>Get Example</h1>

<form method="get" action="get.php">

<label for="name">Name:</label>

<input type="text" id="name" name="name"><br>

<input type="submit" name="submit" value="Submit">

</form>

</body>

</html>

2. get.php

<?php

if (isset($_GET['submit'])) {

$name = $_GET['name'];

echo "<p>Hello, $name!</p>";

?>
Output:

Hello , Eren!
18. AN APPLICATION WITH INPUT VALIDATIONS.

<!DOCTYPE html>

<html>

<head>

<title>Login Form</title>

<style>

.error{color:red}

</style>

</head>

<body>

<?php

$emailErr = $passwordErr = "";

$email = $password = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (empty($_POST["email"])) {

$emailErr = "Email is required";

} else {

$email = test_input($_POST["email"]);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

$emailErr = "Invalid email format";

if (empty($_POST["password"])) {

$passwordErr = "Password is required";

} else {

$password = test_input($_POST["password"]);

if (strlen($password) < 8) {

$passwordErr = "Password must be at least 8 characters long";


}

function test_input($data) {

$data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

return $data;

?>

<h2>Login Form</h2>

<form method="post" action="<?php echo

htmlspecialchars($_SERVER["PHP_SELF"]);?>">

<label>Email:</label>

<input type="text" name="email" value="<?php echo $email;?>">

<span class="error">* <?php echo $emailErr;?></span>

<br><br>

<label>Password:</label>

<input type="password" name="password">

<span class="error">* <?php echo $passwordErr;?></span>

<br><br>

<input type="submit" name="submit" value="Submit"></form>

<?php

if ($emailErr == "" && $passwordErr == "" && isset($_POST["submit"])) {

echo "<h2>Login Details:</h2>";

echo "<p>Email: $email</p>";

echo "<p>Password: $password</p>";

?>

</body>

</html>
Output:
19. PHP AND MYSQL CONNECTIVITY

<?php
// Database configuration
$servername = "localhost";
$username = "sample";
$password = "";
$dbname = "sample";

// Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";

// Close connection
mysqli_close($conn);
?>
OUTPUT :

Connected successfully
20. CREATING SIMPLE TABLE WITH CONSTRAINS

<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// SQL query to create table with constraints


$sql = "CREATE TABLE Users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
password VARCHAR(30),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

// Execute query
if (mysqli_query($conn, $sql)) {
echo "Table Users created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

// Close connection
mysqli_close($conn);
?>
OUTPUT :

Table user created successfully


21. INSERTING A DATA IN A ROW IN MYSQL

<?php
// Connect to database
$servername = "localhost";
$username = "sample";
$password = "";
$dbname = "sample";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Insert a new row


$sql = "INSERT INTO Users (firstname, lastname, email, password)
VALUES ('John', 'Doe', 'johndoe@example.com', 'password')";
if (mysqli_query($conn, $sql)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
$sql = "INSERT INTO Users (firstname, lastname, email, password)
VALUES ('David', 'kumar', 'Davidkumar@example.com', 'password')";
if (mysqli_query($conn, $sql)) {
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
$sql = "INSERT INTO Users (firstname, lastname, email, password)
VALUES ('Ram', 'kumar', 'Ramkumar@example.com', 'password')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
OUTPUT :

New record created successfully


22. DELETING A DATA IN A ROW IN MYSQL

<?php
// Connect to database
$servername = "localhost";
$username = "sample";
$password = "";
$dbname = "sample";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Delete a row
$sql = "DELETE FROM Users WHERE id=12";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
OUTPUT:

Record deleted successfully


23. UPDATE AND DISPLAY A DATA IN A ROW IN MYSQL

// Update a row
$sql = "UPDATE Users SET email='newemail@example.com' WHERE id=11";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: <br>" . mysqli_error($conn);
}
OUTPUT:

Record updated successfully.


24. TO APPLY ANY TWO AGGREATE FUNCTIONS USING MYSQL

<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "myDB";

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Example aggregate functions: COUNT() and MAX()

$sql = "SELECT COUNT(*) AS total_rows, MAX(salary) AS max_salary FROM

myguests";

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

if ($result->num_rows > 0) {

// output data of each row

while($row = $result->fetch_assoc()) {

echo "Total number of rows: " . $row["total_rows"]. "<br>";

echo "Maximum salary: " . $row["max_salary"]. "<br>";

} else {

echo "0 results";

$conn->close();

?>
Output :

Total number of rows: 3

Maximum salary: 50000


25. SEARCHING OF DATA BY DIFFERENT CRITERIA

<?php
// Connect to database
$servername = "localhost";
$username = "sample";
$password = "";
$dbname = "sample";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Search data by first name
$firstname = "John";
$sql = "SELECT * FROM Users WHERE firstname='$firstname'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. " - Email: " .
$row["email"]. "<br>";
}
} else {
echo "0 results";
}
// Search data by last name
$lastname = "kumar";
$sql = "SELECT * FROM Users WHERE lastname='$lastname'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. " - Email: " .
$row["email"]. "<br>";
}
} else {
echo "0 results";
}
// Search data by email
$email = "ramkumar@example.com";
$sql = "SELECT * FROM Users WHERE email='$email'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. " - Email: " .
$row["email"]. "<br>";
}
} else {
echo "0 results";
}
// Close connection
mysqli_close($conn);
?>
OUTPUT :

ID: 13 - Name: John Doe - Email: johndoe@example.com


ID: 14 - Name: david kumar - Email: davidkumar@example.com
ID: 15 - Name: ram kumar - Email: ramkumar@example.com
ID: 15 - Name: ram kumar - Email: ramkumar@example.com

You might also like