PHP is a widely used server-side scripting language in web development. It enables developers to build dynamic websites and applications. PHP code runs on the server side and generates HTML pages based on user requests, which are then returned to the browser. PHP supports mixing with HTML and provides a rich set of built-in functions to handle data and interact with databases.
PHP code needs to be embedded in files with a .php extension. PHP code begins with the <?php tag and ends with the ?> tag. For example:
<?php echo "Hello, World!"; ?>
In PHP, variables start with the $ symbol and do not need to declare their data types. For example:
$name = "John"; $age = 20;
The echo statement is used to output the value of a variable to the web page. For example:
echo "My name is " . $name;
PHP supports multiple types of arrays, and you can access their elements using either indexes or associative keys. For example:
$numbers = array(1, 2, 3, 4, 5); $fruits = array("apple" => "red", "banana" => "yellow");
PHP provides several loop structures to iterate over data. For example:
for ($i = 0; $i < 5; $i++) { echo $i; }
foreach ($fruits as $fruit => $color) { echo "The color of $fruit is $color"; }
PHP supports the definition and calling of functions, allowing code reuse and modularity. For example:
function sayHello($name) { echo "Hello, " . $name; } sayHello("John");
PHP makes it easy to interact with databases like MySQL. Here's an example of how to interact with 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); } $sql = "SELECT * FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "Name: " . $row["name"] . " Age: " . $row["age"]; } } else { echo "No results found"; } $conn->close();
This code successfully connects to a database, executes a query, and outputs the results.
This article introduced the basic concepts and syntax rules of PHP, providing a simple and understandable guide for beginners to web development. By learning PHP's basic syntax, control structures, functions, and database operations, readers can master the skills needed to develop dynamic web pages and applications. Continuous practice and further study will help developers improve their PHP programming skills.