All Syntax of PHP

1. Basic Syntax

PHP code is embedded in HTML and starts with the opening tag <?php and ends with ?>:

<?php
echo "Hello, World!";
?>

2. Variables and Data Types

PHP supports various data types and variables must start with a dollar sign $:

$name = "John";
$age = 25;
$salary = 50000.50;

3. Control Flow Statements

Use if-else, switch, while, for, and other statements to control the flow of your PHP code:

// Example of if-else statement
if ($condition) {
  // code to be executed if the condition is true
} else {
  // code to be executed if the condition is false
} // Example of a for loop
for ($i = 0; $i < 5; $i++) {
  // code to be repeated in the loop
}

4. Functions

Define and use functions in PHP:

// Example of a function
function greet($name) {
  echo "Hello, $name!";
}
greet("Alice");

5. Object-Oriented Concepts

PHP supports object-oriented programming. Here's an example of a class and object:

// Example of a class and object
class Car {
  public $brand;
  function start() {
    echo "Car started";
  }
}
$myCar = new Car();
$myCar->brand = "Toyota";
$myCar->start();

6. File Handling

Read from and write to files using PHP:

// Example of file handling
$file = fopen("example.txt", "r");
while (!feof($file)) {
  echo fgets($file) . "
";
}
fclose($file);

7. Database Connectivity

Interact with databases using PHP. Example with MySQL:

// Example of database connectivity
$conn = mysqli_connect("localhost", "username", "password", "database");
$result = mysqli_query($conn, "SELECT * FROM users");
while ($row = mysqli_fetch_assoc($result)) {
  echo "Name: " . $row['name'] . "
";
} mysqli_close($conn);

0 Comment:

Post a Comment