Cheatsheets: HTML, CSS, JavaScript, PHP, SQL, Git and RegExp

W
H
GIT RegExp PHP JS CSS HTML SQL1 SQL2

Basic

HTML DOC

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8"/>
	<title></title>
</head>
<body>

</body>
</html>

Starting Meta Tags

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- other head content after these tags -->

jQuery

<script
	src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
	integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
	crossorigin="anonymous"></script>

Elements

<link href="" rel="stylesheet" />

<script src=""></script>

<div></div>

<h1></h1>

<p></p>

<b></b>
bold
<i></i>
italic
<u></u>
underline
<s></s>
strike-trough
<span></span>

<img src="" alt="">

<hr>
horizontal line

Ordered List

<ol>
	<li></li>
	<li></li>
	<li></li>
</ol>

Form Inputs

Bullet List

<ul>
	<li></li>
	<li></li>
	<li></li>
</ul>

Video

<video controls autoplay loop poster="img.jpg" preload="auto|metadata|none">
	<source src="video.mp4#t=4" type="video/mp4">
</video>
<form></form>

<button></button>

<label></label>

<output></output>

Input Text

<input
	type="text"
	name="firstname"
	pattern="regexp"
	placeholder=""
	size="40">

Input Number

<input
	readonly
	disabled
	type="number"
	value="33"
	min=""
	max="">

Select

<select name="cars">
	<option value="volvo">Volvo</option>
	<option value="saab">Saab</option>
	<option value="fiat">Fiat</option>
	<option value="audi">Audi</option>
</select>

Textarea

<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea>

Slider

<input
	id="slider"
	type="range"
	min="0"
	max="100"
	step="10">

Basics

var some_var;
can change
const some_var;
can't change unless array or object
let some_var;
can change
const funct = (a,b,c)=>{}

Dom Functions

Style list

.style.here = "3px";

document.querySelector('');

document.querySelectorAll('');

.parentNode

.parentElement

.onclick = ()=> {}

.length;

.insertAdjacentHTML('beforeend', '');

.insertAdjacentHTML('afterend', '');

.insertAdjacentHTML('beforestart', '');

.insertAdjacentHTML('afterstart', '');

.innerHTML;

.outerHTML;

.text();

.getAttribute(attr);

.setAttribute(attr,value);

.hasAttribute(attr);
text from element
.trim()
no space beginning and end
.repeat();
repeats string
.submit(function(e){ e.preventDefault(); });

.keyup(function(e){if(e.keyCode == 13){ }}
Key Code
Key
Code
Name
Press any key to get the JavaScript event Key Code

Math

Math.sin(n);
create rotation
Math.cos(n);
create rotation

Basic Function

localStorage.getItem("name");
get local variable
localStorage.setItem("name");
set local variable
setTimeout(function(){ }, 3000);

setInterval(function(){ }, 3000);

window.location.replace('file.php');

String Functions

"12345".slice(0,3);
123
"12345".slice(1);
2345
"12345".slice(-1);
5
"12345".slice(0,-1);
1234
"12345".startsWith(123);
true
"12345".startsWith(234,1);
true
"12345".endsWith("345");
true
"12345".includes("234");
true

Array Functions

for(let key of []){}

[].map((e,i)=>{})
loops trough array
[].push()
add item to end
[].pop()
removes the last item and returns it
[].shift()
removes the first item
...[]
spread the array

Spread Arguments

const spready = (...argum) =>{
	for(let argums of argum) codeBlock(argums); // => a
};
spready('a','b','c','d');

RegExp

regex = new RegExp(/bob/g)
match bob
regex.test(str)
true or false
str.match(regex)
array filled with matches
str.search(regex)
index, -1 = no match
str.replace(regex,'OK')
use $1 for groups
str.split(regex)
like regular split

Exec

regex.execodeBlock(str)
//regex.lastIndex => the index of last match
//Exec[0] => The full matched string
//Exec[1] => substring match

Object Functions

Fetch HTML

fetch(url)
	.then(response => response.text())
	.then(data => {	});

Fetch JSON

fetch(url)
	.then(response => response.json())
	.then(data => {	});

Object.prototype

Object.prototype.function_name = function(){};
for(let key in Obj){}

Object.keys(Obj)
array of keys
Object.getOwnPropertyNames(Obj)
array with own properties

jQuery Functions

Ajax

$.ajax({
	url:"ajax/file.php",
	method:"POST",
	data:{variable:variable, variable:variable},
	success:function(data){		}
});

Each

$.each(obj, function(key,value) {
	alert( key + ": " + value );
});
.click();

.click(function(){});

.dblclick(function(){});

.mouseenter(function(){});

.mouseleave(function(){});

.mousedown(function(){});

.mouseup(function(){});

.hover(function(){});

.focus(function(){});

.blur(function(){});

On

$("p").on({
    mouseenter: function(){
        $(this).css("background-color", "lightgray");
    },
    mouseleave: function(){
        $(this).css("background-color", "lightblue");
    },
    click: function(){
        $(this).css("background-color", "yellow");
    }
}); 
.addClass('');

.css('backgroundColor','red');

.css('color','red');

.fadeToneLine('slow',0.5,function(){ });

.hasClass('');

.on('change',function(){ });

.removeClass('');

.removeClass('');

$(document).ready(function() { });

.children()

.click(function(){ });

.delay(1000);

.find();

.hide();

.html();

.parent()

.show();

.slideDown("slow",function(){ });

.slideUp("slow",function(){ });

.val();

Basics 1

A regex is a string.
It can be used to search, extract validate and transform other strings.
Regex is delimited using forward slashes /example/
other delimiter like !example! can help with readability, as this
delimiter has to be escaped. 

Basics 2

So matching: "http://"
Requires: /http:\/\//
Where you could also do: !http://!

Every character you type is an instruction to match so:
" " is a search for a single space and "  " for two spaces.

Basics 3

Example
Input: "Life is like a box" jimmy, '2022!'

Regex
/"(?<quoted_text>[^"]+).*?[^0-9](?<year>[0-9]{4})(?:[^0-9]|$)/si

Output:
match -> "Life is like a box" jimmy, '2022!
quoted_text -> Life is like a box
year -> 2022

Basics 4

" 						<- first match double quote.
[^"]+					<- followed by one or more non double quotes greedy.
(?<quoted_text> )		<- all inside a named capture group.
.*? 					<- then match any amount, zero or more of any character (including newlines using the s flag at the end), non greedy.
[^0-9][0-9]{4}			<- then any non number followed by 4 numbers.
(?<year> ) 				<- with the 4 numbers inside a named capture group.
[^0-9]|$ 				<- followed by a non number or the end of the input.
(cat|dog) vs cat|dog	<- This 'or' operator | is placed in a group so it is contained and not applied to the entire regex.
(?: )					<- the group is made non capturing to keep it out of the match result.

greedy vs lazy

// input:
"wow a Tic-Tac-Toe"

// greedy regex (default):
"/a.*c/" -> "a Tic-Tac"

// lazy regex (add ?):
"/a.*?c/" -> "a Tic"

Groups

(example)
Capturing Group
(?:example)
Non capturing group
(?=example)
Positive non matching group
(?!example)
Negative non matching group
\2
match second group
[]
Matches Characters in brackets
[0-9a-z]
Matches range
[^example]
Matches Characters NOT in brackets
|
Either Or
^
Beginning of a String
$
End of a String

PCRE Flags

i
PCRE_CASELESS Ignore case
m
PCRE_MULTILINE reset ^ and $ on newline
s
PCRE_DOTALL . includes newline
x
PCRE_EXTENDED ignored whitespace
A
PCRE_ANCHORED constrained to only match at start of string
D
PCRE_DOLLAR_ENDONLY only match $ at end of string
S
Study
U
PCRE_UNGREEDY flip greedy
X
PCRE_INFO_JCHANGED Allow duplicate names for sub-patterns
S
Study
g
Global search
u
PCRE_UTF8 treat as utf-8

Quantifiers

*
0 or More
+
1 or More
?
0 or One
{3}
Length of 3
{3,4}
Range of Numbers (Min, Max)
{3,}
3 or more

Identifier

.
Any Character Except newline (unless s flag)
\d
Digit (0-9)
\D
Not a Digit (0-9)
\w
Word Character (a-z, A-Z, 0-9, _)
\W
Not a Word Character
\b
Word Boundary (Goes around \w)
\B
Not a Word Boundary
\s
Whitespace (space, tab, newline)
\S
Not Whitespace (space, tab, newline)
\v
Vertical Whitespace
\h
Horizontal Whitespace
\t
Tab
\n
Newline

Functions

attr()
Return: attr value of the element
calcodeBlock()
(100% - 100px)
var()
:root{--color1: red;} p{color: var(--color1);}

Selectors

X Y{ }
Descendant
X + Y{ }
Adjacent
X > Y{ }
Children
a[title]{ }
Attributes
a::first-line
First Line
a[href*="google"]{ }
Anywhere
a[href^="http"]{ }
Beginning
a[href$=".jpg"]{ }
End

State Selectors

a:link{ }
unvisited links
a:visited{ }

a:hover{ }

a:active{ }

::selection{ }
part of an element that is selected
#news:target{ }
active anchor

Input Selectors

input:focus{ }

input:in-range{ }
if within max and min
input:out-of-range{ }
opposite ^
input:indeterminate{ }
js: checkbox.indeterminate = true;
input:invalid{ }

input:valid{ }

input:enabled{ }

input:optional{ }
with no "required" attribute
input::placeholder{ }
input with placeholder
input:read-only{ }
readonly attr. specified

Relation Selectors

p:first-of-type{ }

p:first-child{ }

p:last-child{ }

p:last-of-type{ }

p:nth-child(4){ }

p:nth-child(odd){ }

p:nth-child(even){ }

p:empty{ }
childless
p:only-of-type{ }
select unique
p:only-child{ }
select only children
:not(p){ }
every element but p

Size Units

cm
centimeters
mm
millimeters
in
inches 96px, 2.54cm
pt
points 1.3333px
pc
picas 12pt
em
Relative to elements font-size
ex
Roughly, the height of lowercase letters
ch
relative to the width of the character "0"
rem
Relative to font-size of the root element
vw
Relative to 1% of the width of the viewport
vh
Relative to 1% of the height of the viewport
vmin
Relative to 1% of viewport's smaller dimension
vmax
Relative to 1% of viewport's larger dimension
%
Relative to the parent element

Color Units

#ff0000
Hexadecimal
rgb()
255, 0, 0
rgba()
255, 0, 0, 0.3
hsl();
360, 100%, 50%
hsla()
360, 100%, 50%, 0.3

Position Properties

display

display:inline-block;

position:absolute|fixed|relative|sticky;

float:;
left right
left:;
auto length %
right:;
auto length %
top:;
auto length %
bottom:;
auto length %
margin:;

if "display: flex;"

align-self:
	stretch
	center
	flex-start
	flex-end
	baseline;

vertical-align:;

vertical-align:
	-30px
	baseline
	sub
	super
	top
	text-top
	middle
	bottom
	text-bottom;

Size Properties

height:;

max-height:;

min-height:;

width:;

max-width:;

min-width:;

box-sizing:border-box;
padding & border in width
padding:;

Font Properties

color:;

font-family:;

font-size:;

font-weight:;

line-height:;

text-align:center;

text-decoration:underline;

text-indent:0px;

text-orientation:sideways;

text-shadow:2px 2px red;

word-wrap:break-word;

Other Properties

border

border:
	none
	dotted
	dashed
	solid
	double
	groove
	ridge
	inset
	outset;
border-top-left-radius:;

cursor:text|pointer|grab;

image-orientation:360deg;

opacity:1;

transform-origin:0 0;

transform:scale(),rotate();

box-shadow:x y blur spread color inset?;

visibility:hidden|visible;

z-index:;

select: none

-webkit-user-select: none;
   -moz-user-select: none;
    -ms-user-select: none;
        user-select: none;

columns

-webkit-columns: min-width max-nr;
   -moz-columns: 100px 3;
        columns: 100px 3;

-webkit-column-gap: width;
   -moz-column-gap: 40px;
        column-gap: 40px;

-webkit-column-rule: width style color;
   -moz-column-rule: 4px dotted #ff00ff;
        column-rule: 4px dotted #ff00ff;

   /*if parrent has height*/
   -moz-column-fill: auto|balance;
        column-fill: balance;

Background Properties

background-color:;

background-position:;
center top
background-repeat:;
repeat repeat-x repeat-y no-repeat
background-size:;
auto 200px cover contain
background-image:linear-gradient(),url("2.gif");

Gradient

linear-gradient(direction, colr1 5%, colr2 15%, ...)

repeating-linear-gradient(...)

radial-gradient(circle|ellipse at ...)

repeating-radial-gradient(...)

direction


200px

closest-side

farthest-side

closest-corner

farthest-corner

360deg

Animation

transition

-webkit-transition: all 0.4s ease-in-out;
   -moz-transition: all 0.4s speed;
     -o-transition: all 0.4s speed;
        transition: all 0.4s speed;

animation

@-webkit-keyframes myMove{
    0%{background-color: red;}
    100%{background-color: blue;}
}
@keyframes myMove{
    0%{background-color: red;}
    100%{background-color: blue;}
}
myElement{
    animation-name: myMove;
    animation-duration: 4s;
    animation-delay: -2s;
    animation-iteration-count: 3;
    animation-direction: normal|reverse|alternate|alternate-reverse;
	animation-timing-function:speed;}

speed


ease
slow to fast to slow (default)
linear
same speed
ease-in
slow to normal
ease-out
normal to slow
ease-in-out
slow to normal to slow
cubic-bezier(n,n,n,n)
make
git init
Initialize a git repo for current folder
git clone https://bla.git
make new dir with name of repo
git status
status of the active tree
git add file.txt
stages single file.
git add .
stages all
git add -u
stages modified and deleted, no new
git commit -m ""
update tree. description in ""
git pull
get changes made in GitHub.
git push origin master
upload (optional replace master with branch)
git log
show all commits
git help clone
get help for command
git log --oneline
show all commits on one line
git checkout
get commit. Add branch name or commit id after
git branch
create new branch, add branch name after
git checkout -b
create new branch + checkout, add branch-name after

merge branch with master

git checkout master
git pull origin master
git merge <branchname>
git push origin master
git branch -a
shows all branches
git branch -d
first checkout master. Add branch name after
git revert f6891c9
undo changes made in that version
PRESS shift Press : TYPE wq
after a prompt
git reset f61c9 --hard
stat. must be clean, del commits after this vers.

Basics

Vars

<?php
// A var can be: boolean, integer, double/float, string, array, object, resource, resource(closed), NULL, unknown type

class A {
    public $foo = 1;
}  

$a = new A;
$b = $a;     // $a and $b are copies of the same identifier
             // ($a) = ($b) = <id>
$b->foo = 2;
echo $a->foo."\n";


$c = new A;
$d = &$c;    // $c and $d are references
             // ($c,$d) = <id>

$d->foo = 2;
echo $c->foo."\n";


$e = new A;

function fooneLine($obj) {
    // ($obj) = ($e) = <id>
    $obj->foo = 2;
}

fooneLine($e);
echo $e->foo."\n";

/* The above example will output:
2
2
2
*/
?>

Switch

switch ($case){
	case "Situation 1": $variable = "Situation 1" ; break;
	case "Situation 2": $variable = "Situation 2" ; break;
}
if($variable !== ''){ }

include '../../another.php';

it\'s not hard to write a single quote

"add $variables in strings"

$variable = 'now this';

$variable .= 'and this';

echo "";

print "";

print_r();
Print array
register_shutdown_function('func_name');
On shutdown
file_exists();
Checks if a file or directory exists
memory_get_usage();
Get the current memory usage
memory_get_peak_usage();
Get peak memory usage
uniqid();
Makes a unique ID (non crypto)
serialize();
Makes a value without losing type and structure
unserialize();
Makes a PHP value from serialize
json_encode();
PHP to: JSON on success or false on failure
json_decode();
JSON to: PHP on success or null on failure/nesting limit
gzcompress($sting,$level);
Compress sting, level: 0-9
gzuncompress();
Decompress
file_get_contents($filename);
more
glob('*.php');
Array of files matching
func_get_args();
Array of all functions arguments
setcookie("name", "dude", time()+3600);
Expire in 1 hour

parse_url()

Array(
	[scheme] => 'http'
	[host] => 'hostname'
	[port] => '9090'
	[user] => 'username'
	[pass] => 'password'
	[path] => '/path'
	[query] => 'arg=value'
	[fragment] => 'anchor'
)

getrusage()

Array(
	[ru_oublock] => 0    //block output operations
	[ru_inblock] => 0    //block input operations
	[ru_msgsnd] => 2     //messages sent
	[ru_msgrcv] => 3     //messages received
	[ru_maxrss] => 12692 //maximum resident set size
	[ru_ixrss] => 764    //integral shared memory size
	[ru_idrss] => 3864   //integral unshared data size
	[ru_minflt] => 94    //page reclaims
	[ru_majflt] => 0     //page faults
	[ru_nsignals] => 1   //signals received
	[ru_nvcsw] => 67     //voluntary context switches
	[ru_nivcsw] => 4     //involuntary context switches
	[ru_nswap] => 0      //swaps
	[ru_utime.tv_usec] => 0    //user time used (ms)
	[ru_utime.tv_sec] => 0     //user time used (s)
	[ru_stime.tv_usec] => 6269 //system time used (ms)
	[ru_stime.tv_sec] => 0     //system time used (s)
)

Array functions

For Each

$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
	$value = $value * 2;
}
is_array();
true/false
in_array($needle,$haystack,($strict));

array_unique($array);
Array of unique
array_search($needle,$haystack);
Gets index
array_reverse($array,($preserve_numeric_keys));
Return: Array
array_map(my_func,$array);
Apply function to each
array_diff($array1,$array2);
Return: Array of unique
count($array);
Return: nr of elements in array
max($array);
Return: max value
min($array);
Return: min value
array_rand($array,$nr);
Return: Array of rand keys
array_count_values();
Array([ducks] => 3 [dogs] => 2)
sort();
Update: sorted
asort();
Update: sorted and maintain index
rsort();
Update: reverse sorted
arsort();
Update: reverse sorted and maintain index
implode($glue,$pieces);

explode($glue, $pieces);

array_key_exists($key,$array);
Return: true/false
array_keys($array);
Return: keys
array_values($array);
Return: values
array_push($array, $value1,$value2);
Update: Add to end
array_pop($array);
Update Remove & Return: last value
array_unshift($array, $value1,$value2);
Update: Add to start
array_shift($array);
Update Remove & Return: first value

Splice

$array = array(0,1,2,3);

array_splice($array,2);
becomes 0,1
array_splice($array,1,-1);
becomes 0,3
array_splice($array,1,3,"a");
becomes 0,3
array_splice($array,1,3,array("a","b"));
becomes 1,a,b
array_merge($array1,$array2,$array3);
Returns merged

Scope

Global

$a = 1;
$b = 2;
function test(){
	echo $a; //Error: Undefined variable
	echo $GLOBALS['a']; //1
	global $b; echo $b; //2
}
test();

Static

function counter(){
	//Error: Constant expression contains invalid operations
	static $a = sqrt(9); echo $a;
	//Resets on each run
	$b = 0; echo $b;
	$b++;
	//Increases each call
	static $a = 0; echo $a;
	$a++;
}

Visibility

Scope Resolution Operator ::

class One{
	//constant
	const a = "One const a<br>";
}
echo One::a;

class Two extends One{
	//constant
	const a = "Two const a<br>";
	//static property
	public static $a = "Two static $a<br>";
	//static function
    public static function a(){
		echo "Two funct: parent::a ".parent::a;
        echo "Two funct: self::$a ".self::$a;
    }
}
echo Two::$a; //needs public property
Two::a(); //needs public function can acces private property

$dynamic = "Two";
echo "Two self::a ".$dynamic::a;

Visibility

Class properties

class One{
	public 		$public		= "Public";
	protected	$protected 	= "Protected";
	private		$private 	= "Private";

	function printProperties(){
		echo $this->public;
		echo $this->protected;
		echo $this->private;}
}
$one = new One();
echo $one->public;			// Public
echo $one->protected;		// error: protected property
echo $one->private;			// error: private property
$one->printProperties();	// PublicProtectedPrivate


class Two extends One{
	// You can redeclare public and protected, not private
	public 		$public		= "Public!!";
	protected 	$protected  = "Protected!!";

	function printProperties(){
		echo $this->public;
		echo $this->protected;
		echo $this->private;}
}
$two = new TwoneLine();
echo $two->public;			// Public!!
echo $two->protected;		// error: protected property
echo $two->private;			// error: Undefined property
$two->printProperties();	// Public!!Protected!!Undefined property

Class Methods

class Three{
	public    function goPublic   (){ echo "Public";    }
	protected function goProtected(){ echo "Protected"; }
	private   function goPrivate  (){ echo "Private";   }

	function goPublicAll(){
		$this->goPublicodeBlock();
		$this->goProtected();
		$this->goPrivate();
	}
}
$three = new Three;
$three->goPublicodeBlock();		// Public
$three->goProtected();	// error: protected method
$three->goPrivate();	// error: private method
$three->goPublicAll();	// PublicProtectedPrivate

Superglobal

$GLOBALS
Array of all global variables
$_GET

$_POST

$_FILES
Array of uploaded files to current script via HTTP POST.
$_COOKIE
Array of variables passed to current script via HTTP Cookies.
$_SESSION
After session_start(); you can use it like $GLOBALS
$_REQUEST
Array containing $_GET, $_POST and $_COOKIE.
$_ENV
Array used in combination of putenv()

$_SERVER

Array(
	[PATH] => '/usr/local/bin:/usr/bin:/bin'
	[UNIQUE_ID] => 'dsfdsf@4v23oin'
	[PHPHANDLER] => '/usr/local/php56/bin/php'
	[HTTP_HOST] => 'www.site.com'
	[HTTP_X_REAL_IP] => '132.515.151.11'
	[HTTP_CONNECTION] => 'close'
	[HTTP_USER_AGENT] => 'Mozilla/5.0 (Windows NT 10.0...'
	[HTTP_ACCEPT] => 'text/html,application/xhtml+xml...'
	[HTTP_ACCEPT_LANGUAGE] => 'en-US,en;q=0.7,nl;q=0.3'
	[HTTP_CACHE_CONTROL] => 'no-cache'
	[HTTP_CF_CONNECTING_IP] => '12.515.1551.11'
	[HTTP_CF_IPCOUNTRY] => 'US'
	[HTTP_CF_ORIGIN_HTTPS] => 'off'
	[HTTP_CF_RAY] => '1312c3898j-MXP'
	[HTTP_CF_VISITOR] => '{"scheme":"http"}'
	[HTTP_COOKIE] => '__cfduid=h12048h12308hf1hf9dh9dhhd923h'
	[HTTP_DNT] => '1'
	[HTTP_PRAGMA] => 'no-cache'
	[HTTP_UPGRADE_INSECURE_REQUESTS] => '1'
	[HTTP_X_FORWARDED_PROTO] => 'http'
	[SERVER_SOFTWARE] => 'Apache'
	[SERVER_NAME] => 'www.site.com'
	[SERVER_ADDR] => '34.113.412.44'
	[SERVER_PORT] => '80'
	[REMOTE_HOST] => 'net-13-342-545-11.cust.telforddsl.es'
	[REMOTE_ADDR] => '94.23.44.22.55'
	[DOCUMENT_ROOT] => '/home/username/public_html'
	[SERVER_ADMIN] => 'webmaster@username.com'
	[SCRIPT_FILENAME] => '/home/username/public_html/folder/file.php'
	[REMOTE_PORT] => '14412'
	[GATEWAY_INTERFACE] => 'CGI/1.1'
	[SERVER_PROTOCOL] => 'HTTP/1.0'
	[REQUEST_METHOD] => 'GET'
	[QUERY_STRING] =>
	[REQUEST_URI] => '/folder/file.php'
	[SCRIPT_NAME] => '/folder/file.php'
	[PHP_SELF] => '/folder/file.php'
	[REQUEST_TIME_FLOAT] => '15352156.8289'
	[REQUEST_TIME] => '5415'
);

Names and locations

(__LINE__)
Line number
(__FILE__)
File path
(__DIR__)
Directory path
(__FUNCTION__)
Function name
(__CLASS__)
Class name
(__METHOD__)
Method name
(__NAMESPACE__)
Namespace

PDO

Set up PDO

$sn = "localhost";
$un = "";
$pw = "";
$db = "";

$pdo = new PDoneLine(
	"mysql:
	host=$sn;
	dbname=$db",
	$un,
	$pw);

Insert

$val2 = "val2";

$stmt = $pdo->
prepare(
	"INSERT INTO table_name(col1, col2)
	VALUES("val1", :prepared_val2)");

$stmt->bindParam(
	":prepared_val2",
	$val2, PDO::PARAM_STR);
	$stmt->execute();

Select

$val1 = "val1";

$stmt = $pdo->prepare("
	SELECT col1, col2
	FROM table_name
	where col1 = :prepared_val1");

$stmt->bindParam(
	":prepared_val1",$val1,
	PDO::PARAM_STR);

$stmt->execute(array(":prepared_val1" => $val1));

if ($stmt->rowCount() > 0){
	$check = $stmt->
	fetchAll(PDO::FETCH_ASSOC);
	echo $check[0]["col1"];
}

Update

$val1 = "val1";
$val2 = "val2";

$stmt = $pdo->
prepare(
	"UPDATE table_name
	SET col1 = :prepared_val1
	WHERE col2 = :prepared_val2");

$stmt->bindParam(
	":prepared_val1",
	$val1, PDO::PARAM_STR);

$stmt->bindParam(
	":prepared_val2",
	$val2, PDO::PARAM_STR);
	$stmt->execute();

Select All

The SELECT statement is used to retrieve data from one or more tables in a database.

Retrieve all information about customers.
SELECT * FROM customers;
Retrieve the names and emails of all customers.
SELECT name, email FROM customers;

INSERT Statements

The `INSERT` statement is used to add new rows to a table.

Add a new customer to the database.
INSERT INTO customers (name, email, date_of_birth) 
VALUES ('John Doe', 'john.doe@example.com', '1980-05-15');

UPDATE Statements

The `UPDATE` statement is used to modify existing records in a table.

Update the email address of a customer.
UPDATE customers 
SET email = 'john.newemail@example.com' 
WHERE name = 'John Doe';

DELETE Statements

The `DELETE` statement is used to remove one or more rows from a table.

Remove a customer from the database.
DELETE FROM customers 
WHERE name = 'John Doe';

Nested SELECT Queries

Nested `SELECT` queries, also known as subqueries, are used to perform operations that require querying another result set.

Find customers who have the same email domain as 'example.com' and add best friends name.
SELECT 
  ( SELECT best_friend.firstname
    WHERE best_friend.id = customers.best_friend_id
    LIMIT 1
  ) as best_friend_name,
  email 
FROM customers 
WHERE SUBSTRING_INDEX(email, '@', -1) = (SELECT SUBSTRING_INDEX('example.com', '@', -1));

Working with JSON Data

In modern databases, you can store and query JSON data directly within a table. Assume we have a `customer_details` column in JSON format in the `customers` table.

Retrieve the city from the JSON data.
SELECT JSON_EXTRACT(customer_details, '$.address.city') AS city 
FROM customers;

Advanced Search Techniques

Advanced search techniques can help you perform more complex queries.

Find customers whose names start with 'J' and are older than 30 years.
SELECT name, email 
FROM customers 
WHERE name LIKE 'J%' 
  AND date_of_birth < DATE_SUB(CURDATE(), INTERVAL 30 YEAR);

INSERT Statements

The INSERT statement is used to add new rows to a table.

Add a new customer to the database.
INSERT INTO customers (name, email, date_of_birth) 
VALUES ('John Doe', 'john.doe@example.com', '1980-05-15');

Introduction to Joins

Joins are used to combine rows from two or more tables based on a related column between them.

Join the `customers` and `orders` tables to get a list of customers and their orders.
SELECT customers.name, orders.order_id, orders.order_date 
FROM customers 
JOIN orders ON customers.customer_id = orders.customer_id;

INNER JOIN

The `INNER JOIN` returns records that have matching values in both tables.

Retrieve customers who have placed orders.
SELECT customers.name, orders.order_id 
FROM customers 
INNER JOIN orders ON customers.customer_id = orders.customer_id;

LEFT JOIN

The `LEFT JOIN` returns all records from the left table and the matched records from the right table. The result is NULL from the right side if there is no match.

Retrieve all customers, and if they have placed orders, include the order details.
SELECT customers.name, orders.order_id 
FROM customers 
LEFT JOIN orders ON customers.customer_id = orders.customer_id;

RIGHT JOIN

The `RIGHT JOIN` returns all records from the right table and the matched records from the left table. The result is NULL from the left side if there is no match.

Retrieve all orders, and if there is a customer associated, include the customer details.
SELECT customers.name, orders.order_id 
FROM customers 
RIGHT JOIN orders ON customers.customer_id = orders.customer_id;

FULL JOIN

The `FULL JOIN` returns all records when there is a match in either left or right table records.

Retrieve all customers and all orders, matching where possible.
SELECT customers.name, orders.order_id 
FROM customers 
FULL JOIN orders ON customers.customer_id = orders.customer_id;

CROSS JOIN

The `CROSS JOIN` returns the Cartesian product of the two tables. It combines each row of the first table with each row of the second table.

Generate a list of all possible combinations of customers and orders.
SELECT customers.name, orders.order_id 
FROM customers 
CROSS JOIN orders;

Self Joins

A self join is a regular join but the table is joined with itself.

Find customers who share the same city.
SELECT a.name AS Customer1, b.name AS Customer2 
FROM customers a 
JOIN customers b ON a.city = b.city AND a.customer_id <> b.customer_id;

Handling NULL Values

NULL values represent missing or unknown data. Proper handling of NULL values is essential for accurate queries.

Find customers who have not placed any orders.
SELECT customers.name 
FROM customers 
LEFT JOIN orders ON customers.customer_id = orders.customer_id 
WHERE orders.order_id IS NULL;

Using IS NULL and IS NOT NULL

The `IS NULL` and `IS NOT NULL` operators are used to test for NULL values.

Find all orders that do not have an associated customer (hypothetically).
SELECT order_id 
FROM orders 
WHERE customer_id IS NULL;
Find all customers who have provided their email addresses.
SELECT name 
FROM customers 
WHERE email IS NOT NULL;

Temporary Tables

Temporary tables are used to store intermediate results temporarily during a session.

Create a temporary table to store the results of a complex query.
CREATE TEMPORARY TABLE temp_sales AS
SELECT customer_id, SUM(order_amount) AS total_sales
FROM orders
GROUP BY customer_id;

Common Table Expressions (CTE)

CTEs create temporary result sets that can be referenced within a `SELECT`, `INSERT`, `UPDATE`, or `DELETE` statement.

Use a CTE to simplify a complex query.
WITH SalesCTE AS (
    SELECT customer_id, SUM(order_amount) AS total_sales
    FROM orders
    GROUP BY customer_id
)
SELECT customer_id, total_sales
FROM SalesCTE
WHERE total_sales > 1000;

Recursive CTE

Recursive CTEs are used to work with hierarchical data, such as organizational charts or folder structures.

Use a recursive CTE to list all subordinates of a manager.
WITH RECURSIVE EmployeeHierarchy AS (
    SELECT employee_id, manager_id, employee_name
    FROM employees
    WHERE manager_id IS NULL
    UNION ALL
    SELECT e.employee_id, e.manager_id, e.employee_name
    FROM employees e
    INNER JOIN EmployeeHierarchy eh ON e.manager_id = eh.employee_id
)
SELECT * FROM EmployeeHierarchy;

Window Functions

Window functions perform calculations across a set of table rows related to the current row.

Calculate a running total of sales for each customer.
SELECT customer_id, order_date, order_amount,
       SUM(order_amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_total
FROM orders;

Stored Procedures

Stored procedures encapsulate SQL code for reuse and can include logic and control-of-flow constructs.

Create a stored procedure to add a new customer and return the customer ID.
DELIMITER //

CREATE PROCEDURE AddCustomer (IN name VARCHAR(50), IN email VARCHAR(50), OUT customer_id INT)
BEGIN
    INSERT INTO customers (name, email) VALUES (name, email);
    SET customer_id = LAST_INSERT_ID();
END //

DELIMITER ;

Triggers

Triggers automatically execute SQL code in response to certain events on a table.

Create a trigger to log changes to the orders table.
CREATE TRIGGER log_order_update
AFTER UPDATE ON orders
FOR EACH ROW
BEGIN
    INSERT INTO order_audit (order_id, old_status, new_status, changed_at)
    VALUES (OLD.order_id, OLD.status, NEW.status, NOW());
END;

User-Defined Functions (UDF)

UDFs allow you to create custom functions to perform operations not covered by built-in functions.

Create a UDF to calculate the discount based on the total order amount.
CREATE FUNCTION CalculateDiscount (total_amount DECIMAL(10, 2))
RETURNS DECIMAL(10, 2)
DETERMINISTIC
BEGIN
    DECLARE discount DECIMAL(10, 2);
    IF total_amount > 500 THEN
        SET discount = total_amount * 0.1;
    ELSE
        SET discount = 0;
    END IF;
    RETURN discount;
END;

Event Scheduler

The event scheduler allows you to automate tasks to run at specified times or intervals.

Create an event to archive old orders monthly.
CREATE EVENT archive_old_orders
ON SCHEDULE EVERY 1 MONTH
DO
    INSERT INTO archived_orders
    SELECT * FROM orders WHERE order_date < DATE_SUB(CURDATE(), INTERVAL 1 YEAR);
    DELETE FROM orders WHERE order_date < DATE_SUB(CURDATE(), INTERVAL 1 YEAR);

Partitioning Tables

Partitioning tables can improve performance and manageability by dividing a large table into smaller, more manageable pieces.

Partition an orders table by year.
CREATE TABLE orders (
    order_id INT,
    customer_id INT,
    order_amount DECIMAL(10, 2),
    order_date DATE
)
PARTITION BY RANGE (YEAR(order_date)) (
    PARTITION p0 VALUES LESS THAN (2010),
    PARTITION p1 VALUES LESS THAN (2015),
    PARTITION p2 VALUES LESS THAN (2020),
    PARTITION p3 VALUES LESS THAN MAXVALUE
);

Query Hints

Query hints provide instructions to the optimizer to influence the execution plan of a query.

Use a query hint to limit the execution time of a query.
SELECT /*+ MAX_EXECUTION_TIME(1000) */ *
FROM orders
WHERE order_amount > 100;

Virtual Columns

Virtual columns are computed based on other columns and do not store the data physically.

Create a virtual column for the total price with tax.
CREATE TABLE products (
    product_id INT,
    price DECIMAL(10, 2),
    tax_rate DECIMAL(5, 2),
    total_price DECIMAL(10, 2) GENERATED ALWAYS AS (price * (1 + tax_rate)) STORED
);

Full-Text Search

Full-text search enables efficient text searching within MySQL.

Create a full-text index and search for a term in product descriptions.
CREATE FULLTEXT INDEX idx_description ON products(description);

SELECT * FROM products
WHERE MATCH(description) AGAINST('search term');

Spatial Data Types and Functions

MySQL supports spatial data types for geographic information systems (GIS).

Store and retrieve spatial data.
CREATE TABLE locations (
    id INT,
    name VARCHAR(50),
    coordinates POINT
);

INSERT INTO locations (name, coordinates)
VALUES ('Location A', ST_GeomFromText('POINT(1 1)'));

SELECT id, name, ST_AsText(coordinates) FROM locations;

Indexing

Indexes improve the speed of data retrieval operations by providing a quick way to look up rows.

Create an index on the `email` column in the `customers` table to speed up search queries.
CREATE INDEX idx_email ON customers(email);

Query Optimization

Optimizing queries involves using best practices and tools to make SQL queries run faster.

Use the `EXPLAIN` statement to analyze a query execution plan.
EXPLAIN SELECT * FROM orders WHERE order_date > '2023-01-01';

Caching

Caching stores frequently accessed data in memory for quicker retrieval.

Enable query caching in MySQL.
SET GLOBAL query_cache_size = 1048576;
SET GLOBAL query_cache_type = 1;

Database Normalization

Normalization organizes data to reduce redundancy and improve data integrity.

Normalize a customer orders database to third normal form (3NF).
-- Create separate tables for customers and orders
CREATE TABLE customers (
    customer_id INT PRIMARY KEY,
    name VARCHAR(50),
    email VARCHAR(50)
);

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    order_amount DECIMAL(10, 2),
    order_date DATE,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

Data Security

Securing data involves protecting it from unauthorized access and ensuring privacy.

Grant specific privileges to a user for enhanced security.
GRANT SELECT, INSERT ON database_name.* TO 'username'@'host' IDENTIFIED BY 'password';

Data Encryption

Data encryption ensures that data is protected during transmission and storage.

Enable SSL for MySQL connections.
-- Configuration settings in MySQL my.cnf
[mysqld]
ssl-ca=/path/to/ca.pem
ssl-cert=/path/to/server-cert.pem
ssl-key=/path/to/server-key.pem

Backup and Recovery

Regular backups ensure data can be recovered in case of a failure.

Perform a backup using the `mysqldump` tool.
mysqldump -u username -p database_name > backup_file.sql

Monitoring and Profiling

Monitoring and profiling tools help track database performance and identify bottlenecks.

Use the `slow_query_log` to identify slow-running queries.
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2;