Unit-5 PHP
Unit-5 PHP
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)
Or you can create a table by copying and pasting the following code into the
SQL panel of your
PHPMyAdmin.
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');
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.
<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
function calculateAverage($array) {
return array_sum($array) / count($array);
}
// Driver code
$arr = [10, 20, 30, 40, 50];
$average = calculateAverage($arr);
?>
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.
<?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);
?>
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.
<?php
function calculateAverage($array) {
$sum = array_reduce($array, function($carry, $item) {
return $carry + $item;
}, 0);
?>
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.
<?php
<?php
// 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:
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// closing connection
mysqli_close($conn);
?>
Output:
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:
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
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;
?>
<br><br>
<br><br>
<br><br>
<br><br>
Gender:
<br><br>
</form>
<?php
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
OUTPUT