Code Snippets
PHP Snippets
Base Structure
Echo Statement
<?php echo "Hello, World!"; ?>
Variable Declaration
<?php $name = "John"; ?>
Comment
<?php
// This is a comment
# Another comment
/* Multi-line comment */
?>
Functions
Function Definition
function myFunction() {
// code
}
Function with Return
function add($a, $b) {
return $a + $b;
}
Default Parameter
function greet($name = "Guest") {
echo "Hello, $name";
}
Anonymous Function
$say = function() {
echo "Hello";
};
Single Page PHP
Form Handling
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// process form
}
Get Form Data
$input = $_POST['input'] ?? '';
Redirect
header('Location: index.php');
exit;
Session Start
session_start();
$_SESSION['user'] = 'John';
PHP and Databases
MySQL Connection
$conn = new mysqli('host', 'user', 'pass', 'db');
Query Execution
$result = $conn->query("SELECT * FROM users");
Fetch Data
while($row = $result->fetch_assoc()) {
echo $row['name'];
}
Prepared Statement
$stmt = $conn->prepare("INSERT INTO users (name) VALUES (?)");
$stmt->bind_param('s', $name);
Back to categories