How can PHP be effectively used in a website?
PHP can be effectively used in a website by allowing dynamic content generation, user authentication, form processing, database interactions, and session management. By embedding PHP code within HTML files, developers can create dynamic web pages that can interact with databases, handle user input, and provide personalized content to users.
<?php
// Connect to a database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query database for user information
$user_id = 1;
$sql = "SELECT * FROM users WHERE id = $user_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- How can one protect access to sensitive files in PHP applications using htaccess?
- What best practices should be followed when passing variables in URLs in PHP to ensure proper functionality and avoid errors?
- What are the common pitfalls when trying to display MySQL database content in a table using PHP?