Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
Update Rows with Join
Update rows in one table using values from another table.
UPDATE products p
INNER JOIN categories c
ON c.id = p.category_id
SET p.category_name_cache = c.name
WHERE p.category_id IS NOT NULL;
Find Duplicate Emails
Find duplicate email addresses in a users table.
SELECT email, COUNT(*) AS duplicate_count
FROM users
GROUP BY email
HAVING COUNT(*) > 1
ORDER BY duplicate_count DESC;
Count Rows by Category
Count how many records belong to each category.
SELECT category_id, COUNT(*) AS total_items
FROM products
GROUP BY category_id
ORDER BY total_items DESC;
Select Rows with Pagination
A basic SQL pagination query using LIMIT and OFFSET.
SELECT id, title, created_at
FROM blog_posts
WHERE is_published = 1
ORDER BY created_at DESC
LIMIT 20 OFFSET 40;
Safe JSON Load
Load JSON data from a file and handle invalid JSON safely.
import json
from pathlib import Path
file_path = Path("settings.json")
try:
data = json.loads(file_path.read_text(encoding="utf-8"))
print(data)
except FileNotFoundError:
print("settings.json was not found")
except json.JSONDecodeError:
Simple CSV Reader
Read a CSV file with headers and print selected columns.
import csv
with open("students.csv", newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
name = row.get("name", "")
grade = row.get("grade", "")
print(f"{name}: {grade}")
Count Word Frequency
Count how often each word appears in a short text.
text = "python is fun and python is useful"
words = text.lower().split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
for word, count in counts.items():
print(word, count)
Filter Even Numbers
Filter even numbers from a list using a simple list comprehension.
numbers = [3, 8, 12, 15, 20, 21, 30]
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)
Read Text File Lines
Read a text file line by line and remove the newline characters.
from pathlib import Path
file_path = Path("notes.txt")
if not file_path.exists():
print("File not found")
else:
lines = file_path.read_text(encoding="utf-8").splitlines()
for line_number, line in enumerate(lines, start=1):
Delete Empty Folders
A Windows CMD snippet that removes empty folders under the current directory.
@echo off
for /f "delims=" %%D in ('dir /ad /b /s ^| sort /r') do (
rd "%%D" 2>nul
)
echo Empty folders removed.
pause
Find Text in Files
A Windows CMD command that searches for text inside files.
@echo off
findstr /s /i /n "TODO" *.php
pause
Create Multiple Folders
A small Windows CMD snippet for creating several project folders at once.
@echo off
mkdir src
mkdir public
mkdir assets
mkdir assets\css
mkdir assets\js
mkdir assets\img
echo Project folders created.
pause
List Files by Extension
A Windows CMD command that lists files with a selected extension into a text file.
@echo off
dir /b *.png > png-files.txt
echo File list saved to png-files.txt
pause
Rename All JPG Files in a Folder
A Windows CMD loop that renames all JPG files in the current folder with a numbered prefix.
@echo off
setlocal enabledelayedexpansion
set count=1
for %%F in (*.jpg) do (
ren "%%F" "image-!count!.jpg"
set /a count+=1
)
echo Done.
pause
Safe HTML Escape Helper
A small PHP helper for escaping output in HTML templates.
<?php
function e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$title = '<script>alert("xss")</script>';
echo '<h1>' . e($title) . '</h1>';
Group Array Items by Key
A useful PHP helper for grouping database rows by a selected key.
<?php
function groupByKey(array $items, string $key): array
{
$groups = [];
foreach ($items as $item) {
$groupKey = (string) ($item[$key] ?? '');
if ($groupKey === '') {
continue;
}
CSRF Token Input
A simple PHP pattern for rendering and validating a CSRF token.
<?php
session_start();
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
function csrfInput(): string
{
$token = htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8');
Simple Slug Generator
A compact PHP slug generator for URLs and filenames.
<?php
function makeSlug(string $text): string
{
$text = strtolower(trim($text));
$text = preg_replace('/[^a-z0-9]+/i', '-', $text);
$text = trim((string) $text, '-');
return $text !== '' ? $text : 'item';
}
PDO Select One Row
A safe PDO example for selecting a single row with a prepared statement.
<?php
function findUserByEmail(PDO $pdo, string $email): ?array
{
$stmt = $pdo->prepare(
'SELECT id, email, firstname, lastname
FROM users
WHERE email = :email
LIMIT 1'
);
$stmt->execute([
Filter an Array of Objects
A beginner-friendly JavaScript example for filtering objects by search text.
const snippets = [
{ title: 'PHP Slug Generator', language: 'php' },
{ title: 'CSS Loading Spinner', language: 'css' },
{ title: 'JavaScript Debounce', language: 'javascript' }
];
function searchSnippets(items, query) {
Toggle Dark Mode Class
A tiny dark mode toggle that stores the selected mode in localStorage.
const toggleButton = document.querySelector('[data-theme-toggle]');
const savedTheme = localStorage.getItem('theme');
if (savedTheme === 'dark') {
document.documentElement.classList.add('dark');
}
toggleButton?.addEventListener('click', () => {
Save and Load JSON from localStorage
A safe small helper for storing JSON data in localStorage.
function saveJson(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function loadJson(key, fallback = null) {
try {
const raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) : fallback;
} catch (error) {
Debounce Function
A reusable debounce helper for search inputs and resize handlers.
function debounce(callback, delay = 300) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
callback.apply(this, args);
}, delay);
};
}
const handleSearch = debounce((event) => {
Copy Text to Clipboard
A vanilla JavaScript helper to copy text to the clipboard with a fallback message.
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Copied to clipboard');
return true;
} catch (error) {
console.error('Clipboard copy failed:', error);
return false;
}
}