Group A
Group B
14
Accessing user credentials should be done securely and with respect to user privacy. Generally, user credentials, such as usernames and passwords, are collected through a form on a web page and then processed on the server side using PHP. Here’s a basic example:
HTML Form (login_form.html):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Form</title> </head> <body> <form action="process_login.php" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <label for="password">Password:</label> <input type="password" id="password" name="password" required> <button type="submit">Login</button> </form> </body> </html> |
PHP Processing (process_login.php):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php if ($_SERVER["REQUEST_METHOD"] === "POST") { // Retrieve user credentials from the form $username = isset($_POST["username"]) ? $_POST["username"] : ""; $password = isset($_POST["password"]) ? $_POST["password"] : ""; // Validate credentials (this is a basic example and should be enhanced for security) if ($username === "example_user" && $password === "password123") { echo "Login successful!"; } else { echo "Invalid credentials. Please try again."; } } ?> |
Q.no 15
In PHP, a class is a blueprint or a template that defines the structure and behavior of objects. Objects are instances of a class, and they encapsulate data and related functionality. Here’s a simple example of defining a class in PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php // Define a basic class named 'Person' class Person { // Properties (attributes) public $name; public $age; // Constructor method (executed when an object is created) public function __construct($name, $age) { $this->name = $name; $this->age = $age; } // Method (behavior) public function introduce() { echo "Hi, I'm {$this->name}, and I'm {$this->age} years old."; } } // Create an instance (object) of the 'Person' class $person1 = new Person("John", 25); // Accessing properties and calling methods echo $person1->name; // Output: John echo $person1->age; // Output: 25 $person1->introduce(); // Output: Hi, I'm John, and I'm 25 years old. ?> |
17.
In PHP, you can create functions using the function
keyword followed by the name of the function and a set of parentheses containing optional parameters. Here’s how you can define and use a function in PHP:
1 2 3 4 5 6 7 8 9 |
<?php // Define a simple function named 'greet' function greet($name) { echo "Hello, $name!"; } // Call the 'greet' function greet("John"); // Output: Hello, John! ?> |
Explanation:
– Function Declaration:The function
keyword is used to declare a function, followed by the function name (greet
in this case).
– Parameters:Parameters (also called arguments) are variables that are passed into the function. In the example, the greet
function accepts one parameter named $name
.
– Function Body: The function body contains the code that defines the behavior of the function. In this case, it simply outputs a greeting message using the provided name.
– Calling the Function: To use a function, you simply write its name followed by parentheses containing any required arguments. In the example, we call the greet
function and pass the string "John"
as the argument.
Functions can also return values using the return
statement. Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 |
<?php // Define a function named 'add' that returns the sum of two numbers function add($a, $b) { $sum = $a + $b; return $sum; } // Call the 'add' function and store the result in a variable $result = add(5, 3); // $result will contain the value 8 echo "The sum is: $result"; // Output: The sum is: 8 ?> |
In this example, the add
function takes two parameters $a
and $b
, calculates their sum, and returns the result using the return
statement.
Functions are essential for organizing and reusing code in PHP applications. They allow you to encapsulate logic into reusable units, making your code more modular, maintainable, and easier to understand.
Here’s a basic example of connecting PHP to a MySQL database and inserting data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php // Database connection parameters $host = 'localhost'; $username = 'username'; $password = 'password'; $database = 'dbname'; // Create a connection to the database $conn = mysqli_connect($host, $username, $password, $database); // Check if the connection was successful if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Sample data to be inserted $name = "John Doe"; $age = 30; // Prepare the SQL query $sql = "INSERT INTO users (name, email, age) VALUES ('$name', '$email', $age)"; // Execute the SQL query if (mysqli_query($conn, $sql)) { echo "New record inserted successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // Close the database connection mysqli_close($conn); ?> ``` |
21.
Below is an example of a server-side PHP script that demonstrates inserting and retrieving data to and from a database table using HTML forms:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
```php <?php // Database connection parameters $host = 'localhost'; $username = 'your_username'; $password = 'your_password'; $database = 'your_database'; // Create a connection to the database $conn = mysqli_connect($host, $username, $password, $database); // Check if the connection was successful if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Handle form submission for inserting data if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) { // Sanitize user input to prevent SQL injection $name = mysqli_real_escape_string($conn, $_POST['name']); $email = mysqli_real_escape_string($conn, $_POST['email']); $age = mysqli_real_escape_string($conn, $_POST['age']); // Insert data into the database $sql = "INSERT INTO users (name, email, age) VALUES ('$name', '$email', '$age')"; if (mysqli_query($conn, $sql)) { echo "Data inserted successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } } // Retrieve data from the database $sql = "SELECT * FROM users"; $result = mysqli_query($conn, $sql); // Close the database connection mysqli_close($conn); ?> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Database Example</title> </head> <body> <h2>Insert Data</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> Name: <input type="text" name="name" required><br> Email: <input type="email" name="email" required><br> Age: <input type="number" name="age" required><br> <input type="submit" name="submit" value="Submit"> </form> <h2>Display Data</h2> <table border="1"> <tr> <th>Name</th> <th>Email</th> <th>Age</th> </tr> <?php // Display retrieved data in a table if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td>" . $row['name'] . "</td>"; echo "<td>" . $row['email'] . "</td>"; echo "<td>" . $row['age'] . "</td>"; echo "</tr>"; } } else { echo "<tr><td colspan='3'>No data found</td></tr>"; } ?> </table> </body> </html> ``` |
In this example:
– Replace 'localhost'
, 'your_username'
, 'your_password'
, and 'your_database'
with your actual database connection details.
– The script first establishes a connection to the database and checks for successful connection.
– It handles form submission using the POST
method to insert data into the database table.
– It retrieves data from the database and displays it in an HTML table.
– The form fields include Name, Email, and Age for inserting data.
– The HTML form submits data to the same PHP script for processing ($_SERVER["PHP_SELF"]
).
– Data insertion and retrieval are handled using PHP’s MySQLi extension.
– Proper error handling and SQL injection prevention techniques are applied.
This example provides a basic illustration of how to insert and retrieve data to and from a database table using PHP and HTML forms.
Here’s a simple PHP program to display the sum and average of 10 numbers stored in an array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php // Define an array of 10 numbers $numbers = array(10, 20, 30, 40, 50, 60, 70, 80, 90, 100); // Calculate the sum of numbers $sum = array_sum($numbers); // Calculate the average of numbers $count = count($numbers); $average = $sum / $count; // Display the sum and average echo "Sum of numbers: $sum<br>"; echo "Average of numbers: $average"; ?> |
In this program:
– We define an array $numbers
containing 10 integer values.
– We use the array_sum()
function to calculate the sum of all elements in the array.
– We use the count()
function to get the number of elements in the array, which is used to calculate the average.
– Finally, we display the sum and average of the numbers.