Explore

Explore snippets

Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.

Public snippets by CodShot user
Clear
105 public snippets
Open
SQL
Public

Update Rows with Join

Update rows in one table using values from another table.

SQL Preview
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;
#sql #update #join #mysql
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #87
Open
SQL
Public

Find Duplicate Emails

Find duplicate email addresses in a users table.

SQL Preview
SELECT email, COUNT(*) AS duplicate_count
FROM users
GROUP BY email
HAVING COUNT(*) > 1
ORDER BY duplicate_count DESC;
#sql #duplicates #email #data-cleanup
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #86
Open
SQL
Public

Count Rows by Category

Count how many records belong to each category.

SQL Preview
SELECT category_id, COUNT(*) AS total_items
FROM products
GROUP BY category_id
ORDER BY total_items DESC;
#sql #group-by #count #report
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #85
Open
SQL
Public

Select Rows with Pagination

A basic SQL pagination query using LIMIT and OFFSET.

SQL Preview
SELECT id, title, created_at
FROM blog_posts
WHERE is_published = 1
ORDER BY created_at DESC
LIMIT 20 OFFSET 40;
#sql #pagination #query #beginner
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #84
Open
Python
Public

Safe JSON Load

Load JSON data from a file and handle invalid JSON safely.

Python Preview
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:
#python #json #file #error-handling
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #83
Open
Python
Public

Simple CSV Reader

Read a CSV file with headers and print selected columns.

Python Preview
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}")
#python #csv #file #student
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #82
Open
Python
Public

Count Word Frequency

Count how often each word appears in a short text.

Python Preview
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)
#python #string #dictionary #beginner
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #81
Open
Python
Public

Filter Even Numbers

Filter even numbers from a list using a simple list comprehension.

Python Preview
numbers = [3, 8, 12, 15, 20, 21, 30]

even_numbers = [number for number in numbers if number % 2 == 0]

print(even_numbers)
#python #list #beginner #filter
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #80
Open
Python
Public

Read Text File Lines

Read a text file line by line and remove the newline characters.

Python Preview
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):
#python #file #beginner #text
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #79
Open
Batch
Public

Delete Empty Folders

A Windows CMD snippet that removes empty folders under the current directory.

Batch Preview
@echo off

for /f "delims=" %%D in ('dir /ad /b /s ^| sort /r') do (
    rd "%%D" 2>nul
)

echo Empty folders removed.
pause
#cmd #windows #cleanup #folders
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #78
Open
Batch
Public

Find Text in Files

A Windows CMD command that searches for text inside files.

Batch Preview
@echo off

findstr /s /i /n "TODO" *.php

pause
#cmd #windows #search #files
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #77
Open
Batch
Public

Create Multiple Folders

A small Windows CMD snippet for creating several project folders at once.

Batch Preview
@echo off

mkdir src
mkdir public
mkdir assets
mkdir assets\css
mkdir assets\js
mkdir assets\img

echo Project folders created.
pause
#cmd #windows #folders #utility
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #76
Open
Batch
Public

List Files by Extension

A Windows CMD command that lists files with a selected extension into a text file.

Batch Preview
@echo off

dir /b *.png > png-files.txt

echo File list saved to png-files.txt
pause
#cmd #windows #files #beginner
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #75
Open
Batch
Public

Rename All JPG Files in a Folder

A Windows CMD loop that renames all JPG files in the current folder with a numbered prefix.

Batch Preview
@echo off
setlocal enabledelayedexpansion

set count=1

for %%F in (*.jpg) do (
    ren "%%F" "image-!count!.jpg"
    set /a count+=1
)

echo Done.
pause
#cmd #windows #rename #file-system
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #74
Open
PHP
Public

Safe HTML Escape Helper

A small PHP helper for escaping output in HTML templates.

PHP Preview
<?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>';
#php #security #xss #helper
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #73
Open
PHP
Public

Group Array Items by Key

A useful PHP helper for grouping database rows by a selected key.

PHP Preview
<?php

function groupByKey(array $items, string $key): array
{
    $groups = [];

    foreach ($items as $item) {
        $groupKey = (string) ($item[$key] ?? '');

        if ($groupKey === '') {
            continue;
        }
#php #array #utility #beginner
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #72
Open
PHP
Public

CSRF Token Input

A simple PHP pattern for rendering and validating a CSRF token.

PHP Preview
<?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');
#php #csrf #security #form
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #71
Open
PHP
Public

Simple Slug Generator

A compact PHP slug generator for URLs and filenames.

PHP Preview
<?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';
}
#php #slug #string #utility
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #70
Open
PHP
Public

PDO Select One Row

A safe PDO example for selecting a single row with a prepared statement.

PHP Preview
<?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([
#php #pdo #sql #security
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #69
Open
JavaScript
Public

Filter an Array of Objects

A beginner-friendly JavaScript example for filtering objects by search text.

JavaScript Preview
const snippets = [
  { title: 'PHP Slug Generator', language: 'php' },
  { title: 'CSS Loading Spinner', language: 'css' },
  { title: 'JavaScript Debounce', language: 'javascript' }
];

function searchSnippets(items, query) {
#javascript #array #filter #beginner
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #68
Open
JavaScript
Public

Toggle Dark Mode Class

A tiny dark mode toggle that stores the selected mode in localStorage.

JavaScript Preview
const toggleButton = document.querySelector('[data-theme-toggle]');
const savedTheme = localStorage.getItem('theme');

if (savedTheme === 'dark') {
  document.documentElement.classList.add('dark');
}

toggleButton?.addEventListener('click', () => {
#javascript #dark-mode #ui #localstorage
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #67
Open
JavaScript
Public

Save and Load JSON from localStorage

A safe small helper for storing JSON data in localStorage.

JavaScript Preview
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) {
#javascript #localstorage #json #utility
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #66
Open
JavaScript
Public

Debounce Function

A reusable debounce helper for search inputs and resize handlers.

JavaScript Preview
function debounce(callback, delay = 300) {
  let timerId;

  return function (...args) {
    clearTimeout(timerId);

    timerId = setTimeout(() => {
      callback.apply(this, args);
    }, delay);
  };
}

const handleSearch = debounce((event) => {
#javascript #debounce #search #utility
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #65
Open
JavaScript
Public

Copy Text to Clipboard

A vanilla JavaScript helper to copy text to the clipboard with a fallback message.

JavaScript Preview
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;
  }
}
#javascript #clipboard #utility #beginner
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #64
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support