php_experiments
php_experiments
1. Array Functions
PHP Code:
<?php
// Simple array functions for beginners
// 1. Create an array
$numbers = array(1, 2, 3, 4, 5);
Output:
Sum: 15
Maximum: 5
Sorted Asc: 1, 2, 3, 4, 5
Reversed: 5, 4, 3, 2, 1
<?php
// User defined function to add two numbers
function add($a, $b) {
return $a + $b;
}
Output:
3. Factorial of a Number
PHP Code:
<?php
// Function to calculate factorial
function factorial($n) {
if ($n == 0) return 1;
else return $n * factorial($n - 1);
}
// Calculate factorial of 5
echo "Factorial of 5: " . factorial(5) . "<br>";
?>
Output:
Factorial of 5: 120
4. File Manipulation
PHP Code:
<?php
// Creating a simple text file and writing data to it
$file = fopen("testfile.txt", "w");
fwrite($file, "Hello, this is a test file.");
fclose($file);
Output:
5. Session
PHP Code:
<?php
// Starting a session
session_start();
Output:
6. Cookie Creation
PHP Code:
<?php
// Setting a cookie
setcookie("username", "JohnDoe", time() + (86400 * 30), "/"); // 1 day expiry
Output:
<!DOCTYPE html>
<html>
<head>
<title>Travel Agency</title>
</head>
<body>
<h1>Welcome to XYZ Travel Agency</h1>
<p>Book your dream vacation with us!</p>
<ul>
<li>Destination: Paris</li>
<li>Duration: 7 Days</li>
<li>Cost: $1500</li>
</ul>
</body>
</html>
Output:
<?php
// Assuming connection is already established
$sql = "CREATE TABLE Customers (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50)
)";
if ($conn->query($sql) === TRUE) {
echo "Table Customers created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
?>
Output:
<?php
// Assuming connection is already established
$sql = "INSERT INTO Customers (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
Output:
<?php
// Assuming connection is already established
$sql = "UPDATE Customers SET lastname='Smith' WHERE id=1";
Output:
<?php
// Assuming connection is already established
$sql = "SELECT id, firstname, lastname, email FROM Customers";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
?>
Output: