Nothing Special   »   [go: up one dir, main page]

Unit-5 PHP

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

1.

How to fetch data from localserver database and


display on HTML table using PHP ?

Follow the steps given below:


1. Creating Database: First, we will create a database named ‘geeksforgeeks’. You
can use your existing database or create a new one.

2. Create Table: Create a table named ‘userdata’. The table contains four fields:
 username – varchar(100)
 problems – int(11)
 score – int(11)
 articles – int(11)

Your table structure should look like this:

Or you can create a table by copying and pasting the following code into the
SQL panel of your
PHPMyAdmin.

CREATE TABLE IF NOT EXISTS `userdata` (


`username` varchar(100) NOT NULL,
`problems` int(11) NOT NULL,
`score` int(11) NOT NULL,
`articles` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

To do this from the SQL panel refer to the following screenshot:

create a table ‘userdata” from the SQL panel

Insert records: We will now insert some records into our table. Here we are
inserting 5 records. You can add multiple records.
Or copy and paste the following code into the SQL panel to insert records in the
table.
INSERT INTO `userdata`
(`username`, `problems`, `score`, `articles`)
VALUES ('User-2', '100', '75', '30'), ('User-1', '150', '100', '30'),
('User-3', '200', '50', '10'), ('User-4', '50', '5', '2'), ('User-5',
'0', '0', '1');

To do this from the SQL panel refer to the following screenshot:

we have a database named geeksforgeeks, and a table named userdata. Now, here is
the PHP code to fetch data from the database and display it in an HTML table.

<!-- PHP code to establish connection with the localserver -->


<?php
// Username is root
$user = 'root';
$password = '';

// Database name is geeksforgeeks


$database = 'geeksforgeeks';

// Server is localhost with


// port number 3306
$servername='localhost:3306';
$mysqli = new mysqli($servername, $user,
$password, $database);

// Checking for connections


if ($mysqli->connect_error) {
die('Connect Error (' .
$mysqli->connect_errno . ') '.
$mysqli->connect_error);
}

// SQL query to select data from database


$sql = " SELECT * FROM userdata ORDER BY score DESC ";
$result = $mysqli->query($sql);
$mysqli->close();
?>
<!-- HTML code to display data in tabular format -->
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>GFG User Details</title>
<!-- CSS FOR STYLING THE PAGE -->
<style>
table {
margin: 0 auto;
font-size: large;
border: 1px solid black;
}

h1 {
text-align: center;
color: #006600;
font-size: xx-large;
font-family: 'Gill Sans', 'Gill Sans MT',
' Calibri', 'Trebuchet MS', 'sans-serif';
}

td {
background-color: #E4F5D4;
border: 1px solid black;
}

th,
td {
font-weight: bold;
border: 1px solid black;
padding: 10px;
text-align: center;
}

td {
font-weight: lighter;
}
</style>
</head>

<body>
<section>
<h1>GeeksForGeeks</h1>
<!-- TABLE CONSTRUCTION -->
<table>
<tr>
<th>GFG UserHandle</th>
<th>Practice Problems</th>
<th>Coding Score</th>
<th>GFG Articles</th>
</tr>
<!-- PHP CODE TO FETCH DATA FROM ROWS -->
<?php
// LOOP TILL END OF DATA
while($rows=$result->fetch_assoc())
{
?>
<tr>
<!-- FETCHING DATA FROM EACH
ROW OF EVERY COLUMN -->
<td><?php echo $rows['username'];?></td>
<td><?php echo $rows['problems'];?></td>
<td><?php echo $rows['score'];?></td>
<td><?php echo $rows['articles'];?></td>
</tr>
<?php
}
?>
</table>
</section>
</body>

</html>

PHP – Arrays
The array() Function
The built-in array() function uses the parameters given to it and
returns an object of array type. One or more comma-separated
parameters are the elements in the array.
2. How to Find Average from Array in PHP?
Table of Content
 Using array_sum() and count() Functions
 Using foreach Loop
 Using array_reduce() Function

i) Find Average from Array using array_sum() and


count() Functions
The basic method to find the average is by using the array_sum() function to
calculate the sum of the array elements and the count() function to find the
number of elements in the array.
<?php

function calculateAverage($array) {
return array_sum($array) / count($array);
}

// Driver code
$arr = [10, 20, 30, 40, 50];
$average = calculateAverage($arr);

echo "The average is: " . $average;

?>
Output
The average is: 30
Explanation:
 calculateAverage Function: This function takes an array as an argument
and returns the average of its elements.
 array_sum() Function: Calculates the sum of the array’s elements.
 count() Function: Returns the number of elements in the array.

ii) Find Average from Array in PHP using foreach


Loop
 If you want more control over the calculation, you can use a foreach loop to
iterate through the array and calculate the sum and count manually.

<?php
function calculateAverage($array) {
$sum = 0;
$count = 0;
foreach ($array as $value) {
$sum += $value;
$count++;
}
return $sum / $count;
}

// Driver code
$arr = [10, 20, 30, 40, 50];
$average = calculateAverage($arr);

echo "The average is: " . $average;

?>
Output
The average is: 30
Explanation:
 calculateAverage Function: This function uses a foreach loop to iterate
through the array and calculate the sum and count of its elements.
 $sum and $count Variables: These variables keep track of the sum of the
array’s elements and the number of elements, respectively.
 $sum / $count: Calculates the average by dividing the sum by the count.

iii) Find Average from Array in PHP using


array_reduce() Function
Another way to find the average is by using the array_reduce()
function, which can be used to iteratively reduce the array to a single
value (in this case, the sum of its elements).

<?php

function calculateAverage($array) {
$sum = array_reduce($array, function($carry, $item) {
return $carry + $item;
}, 0);

return $sum / count($array);


}
// Driver code
$arr = [10, 20, 30, 40, 50];
$average = calculateAverage($arr);

echo "The average is: " . $average;

?>
Output
The average is: 30
Explanation:
 calculateAverage Function: This function uses array_reduce() to
calculate the sum of the array’s elements and then divides the sum by the
count of elements to find the average.
 array_reduce() Function: Takes three arguments – the array, a callback
function, and the initial value for the carry. The callback function is
applied iteratively to each element of the array, with $carry being the
result of the previous iteration.

Types of Arrays in PHP


There are three different kind of arrays and each array value is
accessed using an ID which is called the array index.

 Indexed Array − An array which is a collection of values only is


called an indexed array. Each value is identified by a positional
index staring from "0". Values are stored and accessed in
linear fashion.
<?php

$cities = array("New York", "Salt Lake", "Tokyo");


$arrlength = count($cities);

for($i = 0; $i < $arrlength; $i++) {


echo $cities[$i];
echo "<br>";
}
 Associative Array − If the array is a collection of key-value pairs,
it is called as an associative array. The key component of the
pair can be a number or a string, whereas the value part can
be of any type. Associative arrays store the element values in
association with key values rather than in a strict linear index
order.

<?php

$ages = array("Mark" => 22, "Jeff" => 32, "Mike" =>


28);

foreach($ages as $x => $x_value) {


echo "Name = " . $x . ", Age = " . $x_value;
echo "<br>";
}

 Multi Dimensional Array − If each value in either an indexed


array or an associative array is an array itself, it is called a
multi dimensional array. Values are accessed using multiple
indices.

<?php

// Define a multidimensional array


$friends = array(
array(
"name" => "Mark",
"country" => "USA",
),
array(
"name" => "Jeff",
"country" => "Japan",
),
array(
"name" => "Raymond",
"country" => "United Kingdom",
)
);
// Access nested value
echo "Raymond is from " . $friends[2]["country"] . ".";

NOTE − Built-in array functions is given in function


reference PHP Array Functions

 It may be noted that PHP internally considers any of the above


types as an associative array itself. In case of an indexed
array, where each value has index, the index itself is its key.
The var_dump() function reveals this fact

PHP | MySQL ( Creating Database )


What is a database?

Database is a collection of inter-related data which helps in efficient retrieval,


insertion and deletion of data from database and organizes the data in the form of
tables, views, schemas, reports etc. For Example, university database organizes the
data about students, faculty, and admin staff etc. which helps in efficient retrieval,
insertion and deletion of data from it.
We know that in MySQL to create a database we need to execute a query. You may
refer to this article for the SQL query to create data-bases.
The basic steps to create MySQL database using PHP are:
Establish a connection to MySQL server from your PHP script as
described in this article.
 If the connection is successful, write a SQL query to create a database and
store it in a string variable.
 Execute the query.
We have already learnt about establish a connection and creating variables in PHP.
We can execute the query from our PHP script in 3 different ways as described
below:
1) Using MySQLi Object-oriented procedure: If the MySQL connection is
established using Object-oriented procedure then we can use the query()
function of mysqli class to execute our query as described in the below
syntax.
Syntax:
<?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();
?>
Note:Specify the three arguments servername, username and password to the mysqli
object whenever creating a database.

Output:

2) Using MySQLi Procedural procedure: If the MySQL connection is


established using procedural procedure then we can use the mysqli_query()
function of PHP to execute our query as described in the below syntax.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";

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

// Creating a database named newDB


$sql = "CREATE DATABASE newDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully with the name newDB";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

// closing connection
mysqli_close($conn);
?>
Output:

3) Using PDO procedure: If the MySQL connection is established using PDO


procedure then we can execute our query as described in the below syntax.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=newDB", $username,
$password);
// setting the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE newDB";
// using exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully with the name newDB";
}
catch(PDOException $e)
{
echo $sql . "
" . $e->getMessage();
}
$conn = null;
?>
Note:The exception class in PDO is used to handle any problems that may occur in
our database queries. If an exception is thrown within the try{ } block, the script
stops executing and flows directly to the first catch(){ } block.

Output:

PHP Form Handling


The PHP superglobals $_GET and $_POST are used to collect form-data.

GET vs. POST


Both GET and POST create an array (e.g. array( key1 => value1, key2 =>
value2, key3 => value3, ...)). This array holds key/value pairs, where keys are
the names of the form controls and values are the input data from the user.

Both GET and POST are treated as $_GET and $_POST. These are superglobals,
which means that they are always accessible, regardless of scope - and you can
access them from any function, class or file without having to do anything
special.

$_GET is an array of variables passed to the current script via the URL
parameters.

$_POST is an array of variables passed to the current script via the HTTP POST
method.
PHP Forms
<!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>

OUTPUT

You might also like