PHP, as a server-side scripting language, plays a crucial backend role in web development. It is mainly used for handling server-side logic, such as interacting with databases, processing user requests, and generating dynamic web content. Compared to frontend technologies, PHP's main task is to process data in the background, generate webpages, and interact with databases.
Below is a simple PHP code example that demonstrates how PHP connects to a database and performs data queries:
<?php
// Database connection information
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create database connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query data
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
// Output data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();
?>
In this example, PHP establishes a connection to the database, performs an SQL query, and outputs the result to the page. All operations are performed on the server side, which is a typical backend function of PHP.
Although PHP is primarily used for backend development, it works closely with frontend technologies such as HTML, CSS, and JavaScript. Here is a simple example showing how PHP can generate an HTML page with dynamic content:
<?php
$name = "Alice";
?>
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Web Page</title>
</head>
<body>
<h1>Hello, <?php echo $name; ?>!</h1>
<p>Today is <?php echo date("Y-m-d"); ?>.</p>
</body>
</html>
In this example, PHP is embedded within HTML to dynamically insert the value of the variable $name into the webpage, allowing the page content to update based on the backend data.
From the above code examples, it's clear that PHP is primarily used for handling backend logic in web development. It interacts with databases, generates dynamic content, and processes user requests. While PHP can integrate with frontend technologies, its core function remains as a backend language for server-side tasks.