0% found this document useful (0 votes)
6 views25 pages

PHP Programming: Conditional & Looping Statements

The document provides a comprehensive guide on various PHP programming practices, including conditional statements, looping statements, array manipulation, file inclusion, function creation, object-oriented programming, string functions, user registration form validation, and MySQL database operations. Each section includes code examples, expected outputs, and explanations of the functionality. The document serves as a practical reference for PHP developers to understand and implement core programming concepts.

Uploaded by

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

PHP Programming: Conditional & Looping Statements

The document provides a comprehensive guide on various PHP programming practices, including conditional statements, looping statements, array manipulation, file inclusion, function creation, object-oriented programming, string functions, user registration form validation, and MySQL database operations. Each section includes code examples, expected outputs, and explanations of the functionality. The document serves as a practical reference for PHP developers to understand and implement core programming concepts.

Uploaded by

itsparsupatil362
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Practicle 01 : write a program in php to

demonstrate conditional statements in php

if statement :

<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
Output :
12 is even number

If else statement :
Program :
<?php
$num=13;
if($num%2==0)
{
echo "$num is even number";
}
else
{
echo "$num is odd number";
}
?>

Output:
13 is odd number

if else if :
<?php
$marks=69;
if ($marks<33)
{
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>

Output :

B grade

Nested if else :

?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>
Output :

Eligible to give the vote

SWITCH statement :

<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Output :
number is equal to 20

Practicle 02 : write a program in php to


demonstrate looping statements in php

For loop :

<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>

Output :
1
2
3
4
5
6
7
8
9
10

While loop :
<?php

$num = 2;

while ($num < 12) {


$num += 2;
echo $num, "\n";
}

?>
Output :

4
6
8
10
12

Do while loop :

<?php
$n=1;
Do
{
echo "$n<br/>";
$n++;
}
while($n<=10);
?>

Output : 1
2
3
4
5
6
7
8
9
10

Foreach loop :
<?php

$season = array ("Summer", "Winter", "Autumn", "Rainy");

foreach ($season as $element) {


echo "$element";
echo "</br>";
}
?>

Output:
Summer
Winter
Autumn
Rainy

Practicle 03 : write a program in php to create


array,inserted element into array an and accessing
elements from array displaying elements of array.

Inserted Element into array :-


<?php
$original = array( '1','2','3','4','5' );
echo 'Original array : '."\n";
foreach ($original as $x)
{
echo "$x ";
}
$inserted = '$';
array_splice( $original, 3, 0, $inserted );
echo " \n After inserting '$' the array is : "."\n";
foreach ($original as $x)
{echo "$x ";}
echo "\n"
?>

Output-
Original array :
1 2 3 4 5
After inserting '$' the array is :
1 2 3 $ 4 5

Accessing elements from array:-

<?php

// One way to 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";

// Second way to create an indexed array


$name_two[0] = "ZACK";
$name_two[1] = "ANTHONY";
$name_two[2] = "RAM";
$name_two[3] = "SALIM";
$name_two[4] = "RAGHAV";

// Accessing the elements directly


echo "Accessing the 2nd array elements directly:\n";
echo $name_two[2], "\n";
echo $name_two[0], "\n";
echo $name_two[4], "\n";

?>

output:
Accessing the 1st array elements directly:
Ram
Zack
Raghav
Accessing the 2nd array elements directly:
RAM
ZACK
RAGHAV

Practicle 04 :- write a program in php to


demonstrate including multiple files in php
webpage.

<?php require "my_variables.php"; ?>

<?php require "my_functions.php"; ?>

<!DOCTYPE html>

<html lang="en">

<head>

<title><?php displayTitle($home_page); ?></title>

</head>

<body>

<?php include "[Link]"; ?>

<?php include "[Link]"; ?>

<h1>Welcome to Our Website!</h1>

<p>Here you will find lots of useful resources.</p>

<?php include "[Link]"; ?>

</body>

</html>

Output :-
Home | About | Contact

Welcome to Our Website!


Here you will find lots of useful information.

Practicle 05 :- write a program in php to creating


and calling your own functions.

Creating function :-
<?php

function funcGeek()
{
echo "This is Geeks for Geeks";
}

// Calling the function


funcGeek();

?>
Output :-
This is Geeks for Geeks.
Calling function :-

<?php

// function along with three parameters


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

// Calling the function


// Passing three arguments
proGeek(2, 3, 5);

?>
Output :-

The product is 30

Practicle 06 :- write a program in php to declare a


class, creating an object, demonstrate writing
methods and declaring Properties, Accessing
objects.
<?php
// Include class definition
require "[Link]";

// Create multiple objects from the Rectangle class


$obj1 = new Rectangle;
$obj2 = new Rectangle;

// Call the methods of both the objects


echo $obj1->getArea() . "<br>";
echo $obj2->getArea() . "<br>";

// Set $obj1 properties values


$obj1->length = 30;
$obj1->width = 20;
// Set $obj2 properties values
$obj2->length = 35;
$obj2->width = 50;

// Call the methods of both the objects again


echo $obj1->getArea() . "<br>";
echo $obj2->getArea() . "<br>";
?>
Output :-
0
0
600
1750

Practicle 07 :- write a program in php to


demonstrate string functions.
[Link]() - Return the Length of a String
<?php
echo strlen("Hello world!");
?>
Output :-
12
2. str_word_count() - Count Words in a String
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
Output:-
2
3. strrev() - Reverse a String
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
Output:-
!dlrow olleH
[Link]() - Search For a Text Within a String
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
Output:
6
5.str_replace() - Replace Text Within a String
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
Output:-
Hello Dolly!

Practicle 08 :- write a program in php to create /


design a user registration form, validate form data
and display entered form data on webpage

<!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"></t
extarea>
<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>YouInput:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

Output:-

PHP Form Validation Example


Name:

E-mail:

Website:

Comment:

Gender: Female Male Other

Your Input: male


Practicle 09 :- Use MYSQL in command line mode
for following operations :

9.1: Show database


<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname=”my_DB”;

// Create connection

$conn = mysqli_connect($servername, $username,


$password,$dbname);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

echo "Connected successfully";

?>

Output:-
Connected successfully
9.2 create a database :-
<?php

$servername = "localhost";

$username = "root";

$password = "";

// Create connection

$conn = mysqli_connect($servername, $username, $password);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

// Create database

$sql = "CREATE DATABASE myDB";

if (mysqli_query($conn, $sql)) {

echo "Database created successfully";

} else {

echo "Error creating database: " . mysqli_error($conn);

}
mysqli_close($conn);

?>

Output:
Database created successfully

9.3 . Create a Table :-


<?php

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDB";

// Create connection

$conn = mysqli_connect($servername, $username, $password,


$dbname);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

// sql to create table

$sql = "CREATE TABLE MyGuests (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,


firstname VARCHAR(30) NOT NULL,

lastname VARCHAR(30) NOT NULL,

email VARCHAR(50))";

if (mysqli_query($conn, $sql))

echo "Table MyGuests created successfully";

} else {

echo "Error creating table: " . mysqli_error($conn);

mysqli_close($conn);

?>

Output:
Table MyGuests created successfully

9.4 Insert Data Into MySQL


<?php

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDB";
// Create connection

$conn = mysqli_connect($servername, $username, $password,


$dbname);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

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

VALUES ('Mahesh', 'Patil', 'mahesh@[Link]')";

if (mysqli_query($conn, $sql)) {

echo "New record created successfully";

} else {

echo "Error: " . $sql . "<br>" . mysqli_error($conn);

mysqli_close($conn);

?>

Output:-
New record created successfully
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Output:-
Record deleted successfully.

Practicle 10 :- write a program in php to


connecting to MYSQL and selecting the database,
executing simple queries and retrieving query
result.
Select Data From a MySQL Database:-
<!DOCTYPE html>
<html>
<body>

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

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

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


$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"]. "<br>";
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

</body>
</html>

Output:-
id: 1 - Name: John Doe
id: 2 - Name: Mary Moe
id: 3 - Name: Julie Dooley

Retrieving Query Results:-

<html>
<body>

<?php

$username = "root";

$password = "";

$database = "mydb";

$conn = mysqli_connect("localhost", $username, $password,


$database);

$query = "SELECT * FROM tblinfo";

echo '<table border="2" cellspacing="2" cellpadding="2">

<tr>

<td> <font face="Arial">ID</font> </td>

<td> <font face="Arial">Emp Name</font> </td>

<td> <font face="Arial">Class Name</font> </td>

<td> <font face="Arial">Address</font> </td>

</tr>';

$result = mysqli_query($conn,$query);

if(mysqli_num_rows($result)>0)

{
while ($row = mysqli_fetch_assoc($result))

$field1name = $row["id"];

$field2name = $row["name"];

$field3name = $row["class"];

$field4name = $row["address"];

echo '<tr>

<td>'.$field1name.'</td>

<td>'.$field2name.'</td>

<td>'.$field3name.'</td>

<td>'.$field4name.'</td>

</tr>';

mysqli_close($conn);

?>

</body>

</html>

Output:-
Id Emp Name Class Name Address
1 Madhav Rajegave MCA Latur
3 Ajinkya Rajegave MBBS Latur
4 Aditya Rajegave MBBS Latur
5 Aditya Raje MBBS Ausa
6 NA Mhetre MBBS Ausa
8 Mohan Lawate MCS Latur
11 Ravi MCS Latur

You might also like