PHP is a popular server-side scripting language used to create dynamic web pages. It stands for "PHP: Hypertext Preprocessor." PHP is embedded in HTML and is especially suited for web development because it can be executed on the server, which generates HTML to send to the client. This guide will introduce you to PHP and provide example codes to help you get started.
What is PHP?
PHP is a scripting language that runs on the server. It can connect to databases, handle form submissions, and create dynamic web content. PHP code is written between <?php ... ?>
tags.
Basic Syntax
PHP code is embedded within HTML and starts with <?php
and ends with ?>
. Here is a simple example:
<!DOCTYPE html>
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<h1>Welcome to My PHP Page</h1>
<?php
echo "Hello, World!";
?>
</body>
</html>
Variables in PHP
Variables in PHP start with a dollar sign ($
). Here is how you declare and use variables:
<?php
$greeting = "Hello, World!";
echo $greeting;
?>
PHP and HTML Forms
PHP is often used to process data from HTML forms. Here is an example of a simple form and how PHP can handle the form data:
HTML Form
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<form method="post" action="process_form.php">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP Form Processing
<?php
$name = $_POST['name'];
$email = $_POST['email'];
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
?>
Connecting to a Database
PHP can connect to databases such as MySQL. Here is an example of connecting to a MySQL database and retrieving data:
Database Connection
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Retrieving Data
<?php
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Conclusion
PHP is a powerful and flexible language for creating dynamic web content. With PHP, you can handle form submissions, interact with databases, and generate dynamic HTML. The examples provided here are just the beginning. Practice writing PHP code to become more familiar with its capabilities and how it can be used to enhance your web development projects.