Useful code examples and solutions I've collected. Feel free to use and learn from them!
// Array Map in JavaScript
// Transform array elements using the map function
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// PHP Database Connection
// Secure database connection using PDO
<?php
try {
$pdo = new PDO(
"mysql:host=localhost;dbname=mydb",
"username",
"password"
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
// CSS Flexbox Centering
// Center elements using flexbox
.container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.centered-item {
padding: 2rem;
background: white;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
// Python List Comprehension
// Create lists using comprehension syntax
# Basic list comprehension
squares = [x**2 for x in range(10)]
print(squares)
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)
# Nested comprehension
matrix = [[i+j for j in range(3)] for i in range(3)]
print(matrix)
// React useState Hook
// Managing state in functional components
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={() => setCount(count - 1)}>
Decrement
</button>
</div>
);
}
export default Counter;
// SQL JOIN Query
// Join multiple tables to get related data
SELECT
users.name,
orders.order_date,
products.product_name,
order_items.quantity
FROM users
INNER JOIN orders ON users.id = orders.user_id
INNER JOIN order_items ON orders.id = order_items.order_id
INNER JOIN products ON order_items.product_id = products.id
WHERE users.id = 1
ORDER BY orders.order_date DESC;