0% found this document useful (0 votes)
20 views20 pages

PHP Programs 1-10

The document contains a series of PHP programming exercises demonstrating various concepts such as looping statements, conditional statements, arrays, file inclusion, functions, classes, string functions, user registration forms, and MySQL operations. Each exercise includes code snippets, expected outputs, and explanations of the functionality. The document serves as a comprehensive guide for learning PHP programming techniques and database interactions.

Uploaded by

balajikamble4321
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)
20 views20 pages

PHP Programs 1-10

The document contains a series of PHP programming exercises demonstrating various concepts such as looping statements, conditional statements, arrays, file inclusion, functions, classes, string functions, user registration forms, and MySQL operations. Each exercise includes code snippets, expected outputs, and explanations of the functionality. The document serves as a comprehensive guide for learning PHP programming techniques and database interactions.

Uploaded by

balajikamble4321
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
You are on page 1/ 20

Practicle 01 : Write a program in PHP to

demonstrate looping statements in PHP.

For loop: echo”</br>”;


}
<?php ?>
For($n=1;$n<=10;$n++){
echo $n, "\n";
}
?>

Output: Output:
1 2 3 4 5 6 7 8 9 10
Summer
While loop: Winter
Autumn
<?php Rainy
$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, “\n”;
$n++;
}
While($n<=10);;
?>

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

For each loop:

<?php
$season =
array(“Summer”,”Winter”,”Autumn”,”Rainy”);
foreach($season as $element) {
echo”$element”;
Practicle 02 : Write a program in PHP to
demonstrate conditional statements in PHP.

If statement : else if($marks>=65 && $marks<80) {


echo”B grade”;
<?php }
$num=12; else if($marks>=80 && $marks<90) {
if($num%2==0){ echo”A grade”;
echo"$num is even number"; }
}else{
echo"$num is odd number";
} else if($marks>=90 && $marks<100) {
echo”A+ grade”;
Output: }
12 is even number else{
echo”Invalid input”;
If else statement : }
?>
<?php
$num=13; Output:
If($num%2==0) B grade
{
echo”$num is even number”; Nested If else statement :
}
Else <?php
{ $age=23;
Echo”$num is odd number”; $nationality = “Indian”;
} //applying conditions on nationality and age
?> if($nationality == “Indian”)
{
Output: if($age >= 18){
13 is odd number echo”Eligible to give vote”;
}
If else If statement : else{
echo”Not eligible to give vote”;
<?php }
$marks=69; }
If($marks<33) ?>
{
echo”fail”; Output:
} Eligible to give the vote
else if($marks>=34 && $marks<50) {
echo”D grade”; SWITCH statement :
}
else if($marks>=50 && $marks<65) { <?php
echo”C grade”; $num=20;
} Switch($num){
Case 10:
echo(“number is equal 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
Parcticle 03 : Write a program in PHP to
Create an Array, Insert elements in Array,
Accessing Elements form Array and
Displaying elements of Arrays.

Insert elements in Array: echo "Accessing the 2nd array elements


<?php directly:<br>";
$original = array( '1','2','3','4','5'); echo $name_two[2], "<br>";
echo 'Original array : '."\n"; echo $name_two[0], "<br>";
foreach ($original as $x) echo $name_two[4], "<br>";
{
echo "$x "; ?>
}
$inserted = '$';
array_splice( $original, 3, 0, $inserted );
echo " \nAfter inserting '$' the array is : "."
\n";
foreach ($original as $x) Output:
{echo "$x ";} Accessing the 1st array elements directly:
echo "\n" Harshad
?> Sumit
Paresh
Output: Accessing the 2nd array elements directly:
Original array : 1 2 3 4 5 HARSHAD
After inserting '$' the array is : 1 2 3 $ 4 5 SUMIT
PARESH

Accessing Elements form Array:


<?php
//One way to create an indexed array
$name_one = array("Sumit", "Nishikant",
"Harshad", "Sainath", "Paresh");

//Accessing the elements directly


echo "Accessing the 1st array elements
directly:<br>";
echo $name_one[2], "<br>";
echo $name_one[0], "<br>";
echo $name_one[4], "<br>";

//Second way to create an indexed array


$name_two[0] = "SUMIT";
$name_two[1] = "PARESH";
$name_two[2] = "HARSHAD";
$name_two[3] = "SAINATH";
$name_two[4] = "PARESH";

//Accessing the elements directly


Practicle 04 : Write a program in PHP to demonstrate including multiple files in PHP webpage.

Home.php
<?php require "my_variables.php"; ?><br>
<html>
<head>
<title><?php ($home_page); ?></title>
</head>
<body>
<?php include "header.php"; ?>
<?php include "menu.php"; ?>
<?php include "footer.php"; ?>
<h1>Welcome to Our Website!</h1>
<p>Here you will find lots of useful resources.</p>
</body>
</html>
<?php require "my_functions.php"; ?>

my_functions.php
<html>
<head>
</head>
<body>
<section style="background-color:#bcdeef;width: 30%;border: 0px solid light;">
<h6 style>Copyright <b>&#169;</b> 2024 svm udgir</h6>
</section>
</body>
</html>

my_Variables.php
<html>
<head>
</head>
<body>
<section style="background-color:#bcdeef;width: 30%; border: 0px solid light;">
<h3 style> SVM UDGIR</h3>
</section>
</body>
</html>

header.php
<html>
<head>
</head>
<body>
<a href=Home>Home |</a>
</body>
</html>
menu.php
<html>
<head>
</head>
<body>
<a href=About>About |</a>
</body>
</html>

footer.php
<html>
<head>
</head>
<body>
<a href="contact">Contact</a>
</body>
</html>

Output:

SVM UDGIR

Home | About | Contact

Welcome to Our Website!


Here you will find lots of useful resources.

Copyright © 2024 svm udgir


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 functions


//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 "Rectangle.php"

//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.

1.strlen() – 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!”);
?>

Output:
2

3. strrev() – Reverse a String

<?php
echo strrev(“Hello world!”); //output
?>

Output:
!dlrow olleH

4.strpos() – Search For a Text Within a String

<?php
echo strpos(“Hello World!”, “World”);
?>

Output:
6

5.str_replace() – Replace Text Within a String

<?php
echo str_replace(“world”, “Dolly”, “Hello world!”);
?>

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

Output:
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.4 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.5 Add data in to 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 = “INSERT INTO MyGuests(firstname, lastname, email)
VALUES (‘Harshad’, ‘Badnale’, ‘[email protected]’)”;
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

9.6 Select data from table

<?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 = "SELECT id, firstname, lastname FROM MyGuests";
$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();
?>

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

9.7 Rename a table

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_errno) {
printf("Connect failed: %s", $mysqli->connect_error);
exit();
}
$sql = "RENAME TABLE Student TO Employee ";
if ($mysqli->query($sql)) {
printf("table renamed successfully.");
}
if ($mysqli->errno) {
printf("table could not rename: %s", $mysqli->error);
}
$mysqli->close();

Output:
table renamed successfully.

9.8 Delete data from table

<?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 to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>

Output:
Record deleted successfully

9.9 Delete a Table

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

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($mysqli→connect_errno ) {
printf("Connect failed: %s<br />", $mysqli→connect_error);
exit();
}
printf('Connected successfully.<br />');

if ($mysqli→query("Drop Table tutorials_tbl")) {


printf("Table dropped successfully.<br />");
}
if ($mysqli→errno) {
printf("Could not drop table: %s<br />", $mysqli→error);
}
$mysqli→close();
?>

Output:
Connected successfully
Table dropped successfully.
Practicle 10: Write a program in PHP to connecting to MySQL and selecting
the database,
Executing simple queries, and retrieving query results.

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 Paresh Waichale MCA Latur
3 Harshad Badnale MBBS Latur
4 Sainath kedase MBBS Latur
5 Wishnu Wagmare MBBS Udgir
6 Partik Dhoble MBBS Udgir
8 Sumit Shelhale MCS Latur
11 Parbhudha Firange MCS Latur

You might also like