Although PHP is among the most popular languages in the world, the most used codes around the world are as follows;
1. Variables and Printing:
$variable = "Hello World!"; echo $variable;
?>
2. Conditional Statements:
php $note = 75;
if ($not >= 50) {
echo "You passed";
} else {
echo "You Failed";
}
?>
3. Loops:
for ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . "
";
}
$i = 1;
while ($i <= 5) {
echo "Number: " . $i . "
"; $i++;
}
?>
4. Functions:
function sum($number1, $number2) {
return $number1 + $number2;
}
echo add(5, 3); //Output: 8
?>
5. Array:
$array = array("Apple", "Pear", "Orange");
echo $array[0]; //Output: Apple
foreach ($array as $fruit) {
echo $fruit . "
";
}
?>
$servername = "localhost";
$username = "user_name";
$password = "password";
$dbname = "database";
//Create database connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Error checking
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
// Retrieving data from database
$sql = "SELECT id, name, surname FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//Get the output data rows with a loop
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " " . $row["surname"]. "
";
}
} else {
echo "No record found";
}
// Close the database connection
$conn->close();
?>
File Operations
//Write to file
$file = fopen("test.txt", "w");
fwrite($file, "Hello World!");
fclose($file);
// Reading from file
$file = fopen("test.txt", "r");
echo fread($file, filesize("test.txt"));
fclose($file);
?>
Object Oriented Programming
// Class definition
class Car {
// Properties
public $brand;
public $model;
//Methods
function run() {
return "Car is running";
}
}
// Create object
$car1 = new Car();
$car1->make = "BMW";
$car1->model = "X5";
echo $car1->brand . " " . $car1->model . "
";
echo $car1->run();
?>
Release date : 08.03.2024 Author : Samet Views : 262 Category : Php