<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
</body>
</html><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 --><script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script><link href="" rel="stylesheet" />
<script src=""></script>
<div></div>
<h1></h1>
<p></p>
<b></b>
<i></i>
<u></u>
<s></s>
<span></span>
<img src="" alt="">
<hr>
<ol>
<li></li>
<li></li>
<li></li>
</ol>
<ul>
<li></li>
<li></li>
<li></li>
</ul><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
type="text"
name="firstname"
pattern="regexp"
placeholder=""
size="40"><input
readonly
disabled
type="number"
value="33"
min=""
max=""><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 name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea><input
id="slider"
type="range"
min="0"
max="100"
step="10">var some_var;
const some_var;
let some_var;
const funct = (a,b,c)=>{}
.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);
.trim()
.repeat();
.submit(function(e){ e.preventDefault(); });
.keyup(function(e){if(e.keyCode == 13){ }}
Math.sin(n);
Math.cos(n);
localStorage.getItem("name");
localStorage.setItem("name");
setTimeout(function(){ }, 3000);
setInterval(function(){ }, 3000);
window.location.replace('file.php');
"12345".slice(0,3);
"12345".slice(1);
"12345".slice(-1);
"12345".slice(0,-1);
"12345".startsWith(123);
"12345".startsWith(234,1);
"12345".endsWith("345");
"12345".includes("234");
for(let key of []){}
[].map((e,i)=>{})
[].push()
[].pop()
[].shift()
...[]
const spready = (...argum) =>{
for(let argums of argum) codeBlock(argums); // => a
};
spready('a','b','c','d');regex = new RegExp(/bob/g)
regex.test(str)
str.match(regex)
str.search(regex)
str.replace(regex,'OK')
str.split(regex)
regex.execodeBlock(str)
//regex.lastIndex => the index of last match
//Exec[0] => The full matched string
//Exec[1] => substring matchfetch(url)
.then(response => response.text())
.then(data => { });fetch(url)
.then(response => response.json())
.then(data => { });Object.prototype.function_name = function(){};for(let key in Obj){}
Object.keys(Obj)
Object.getOwnPropertyNames(Obj)
$.ajax({
url:"ajax/file.php",
method:"POST",
data:{variable:variable, variable:variable},
success:function(data){ }
});$.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(){});
$("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();
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. 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.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" <- 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.// input:
"wow a Tic-Tac-Toe"
// greedy regex (default):
"/a.*c/" -> "a Tic-Tac"
// lazy regex (add ?):
"/a.*?c/" -> "a Tic"(example)
(?:example)
(?=example)
(?!example)
\2
[]
[0-9a-z]
[^example]
|
^
$
i
m
s
x
A
D
S
U
X
S
g
u
*
+
?
{3}
{3,4}
{3,}
.
\d
\D
\w
\W
\b
\B
\s
\S
\v
\h
\t
\n
attr()
calcodeBlock()
var()
X Y{ }
X + Y{ }
X > Y{ }
a[title]{ }
a::first-line
a[href*="google"]{ }
a[href^="http"]{ }
a[href$=".jpg"]{ }
a:link{ }
a:visited{ }
a:hover{ }
a:active{ }
::selection{ }
#news:target{ }
input:focus{ }
input:in-range{ }
input:out-of-range{ }
input:indeterminate{ }
input:invalid{ }
input:valid{ }
input:enabled{ }
input:optional{ }
input::placeholder{ }
input:read-only{ }
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{ }
p:only-of-type{ }
p:only-child{ }
:not(p){ }
cm
mm
in
pt
pc
em
ex
ch
rem
vw
vh
vmin
vmax
%
#ff0000
rgb()
rgba()
hsl();
hsla()
display:inline-block;
position:absolute|fixed|relative|sticky;
float:;
left:;
right:;
top:;
bottom:;
margin:;
align-self:
stretch
center
flex-start
flex-end
baseline;vertical-align:
-30px
baseline
sub
super
top
text-top
middle
bottom
text-bottom;height:;
max-height:;
min-height:;
width:;
max-width:;
min-width:;
box-sizing:border-box;
padding:;
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;
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:;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;-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-color:;
background-position:;
background-repeat:;
background-size:;
background-image:linear-gradient(),url("2.gif");
linear-gradient(direction, colr1 5%, colr2 15%, ...)
repeating-linear-gradient(...)
radial-gradient(circle|ellipse at ...)
repeating-radial-gradient(...)
200px
closest-side
farthest-side
closest-corner
farthest-corner
360deg
-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;@-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;}
ease
linear
ease-in
ease-out
ease-in-out
cubic-bezier(n,n,n,n)
git init
git clone https://bla.git
git status
git add file.txt
git add .
git add -u
git commit -m ""
git pull
git push origin master
git log
git help clone
git log --oneline
git checkout
git branch
git checkout -b
git checkout master
git pull origin master
git merge <branchname>
git push origin mastergit branch -a
git branch -d
git revert f6891c9
PRESS shift Press : TYPE wq
git reset f61c9 --hard
<?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 ($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();
register_shutdown_function('func_name');
file_exists();
memory_get_usage();
memory_get_peak_usage();
uniqid();
serialize();
unserialize();
json_encode();
json_decode();
gzcompress($sting,$level);
gzuncompress();
file_get_contents($filename);
glob('*.php');
func_get_args();
setcookie("name", "dude", time()+3600);
Array(
[scheme] => 'http'
[host] => 'hostname'
[port] => '9090'
[user] => 'username'
[pass] => 'password'
[path] => '/path'
[query] => 'arg=value'
[fragment] => 'anchor'
)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)
)$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
$value = $value * 2;
}is_array();
in_array($needle,$haystack,($strict));
array_unique($array);
array_search($needle,$haystack);
array_reverse($array,($preserve_numeric_keys));
array_map(my_func,$array);
array_diff($array1,$array2);
count($array);
max($array);
min($array);
array_rand($array,$nr);
array_count_values();
sort();
asort();
rsort();
arsort();
implode($glue,$pieces);
explode($glue, $pieces);
array_key_exists($key,$array);
array_keys($array);
array_values($array);
array_push($array, $value1,$value2);
array_pop($array);
array_unshift($array, $value1,$value2);
array_shift($array);
$array = array(0,1,2,3);
array_splice($array,2);
array_splice($array,1,-1);
array_splice($array,1,3,"a");
array_splice($array,1,3,array("a","b"));
array_merge($array1,$array2,$array3);
$a = 1;
$b = 2;
function test(){
echo $a; //Error: Undefined variable
echo $GLOBALS['a']; //1
global $b; echo $b; //2
}
test();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++;
}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;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 propertyclass 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$GLOBALS
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
$_REQUEST
$_ENV
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'
);(__LINE__)
(__FILE__)
(__DIR__)
(__FUNCTION__)
(__CLASS__)
(__METHOD__)
(__NAMESPACE__)
$sn = "localhost";
$un = "";
$pw = "";
$db = "";
$pdo = new PDoneLine(
"mysql:
host=$sn;
dbname=$db",
$un,
$pw);$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();$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"];
}$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();The SELECT statement is used to retrieve data from one or more tables in a database.
SELECT * FROM customers;SELECT name, email FROM customers;The `INSERT` statement is used to add new rows to a table.
INSERT INTO customers (name, email, date_of_birth)
VALUES ('John Doe', 'john.doe@example.com', '1980-05-15');
The `UPDATE` statement is used to modify existing records in a table.
UPDATE customers
SET email = 'john.newemail@example.com'
WHERE name = 'John Doe';
The `DELETE` statement is used to remove one or more rows from a table.
DELETE FROM customers
WHERE name = 'John Doe';
Nested `SELECT` queries, also known as subqueries, are used to perform operations that require querying another result set.
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));
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.
SELECT JSON_EXTRACT(customer_details, '$.address.city') AS city
FROM customers;
Advanced search techniques can help you perform more complex queries.
SELECT name, email
FROM customers
WHERE name LIKE 'J%'
AND date_of_birth < DATE_SUB(CURDATE(), INTERVAL 30 YEAR);
The INSERT statement is used to add new rows to a table.
INSERT INTO customers (name, email, date_of_birth)
VALUES ('John Doe', 'john.doe@example.com', '1980-05-15');Joins are used to combine rows from two or more tables based on a related column between them.
SELECT customers.name, orders.order_id, orders.order_date
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id;The `INNER JOIN` returns records that have matching values in both tables.
SELECT customers.name, orders.order_id
FROM customers
INNER JOIN orders ON customers.customer_id = orders.customer_id;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.
SELECT customers.name, orders.order_id
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id;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.
SELECT customers.name, orders.order_id
FROM customers
RIGHT JOIN orders ON customers.customer_id = orders.customer_id;The `FULL JOIN` returns all records when there is a match in either left or right table records.
SELECT customers.name, orders.order_id
FROM customers
FULL JOIN orders ON customers.customer_id = orders.customer_id;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.
SELECT customers.name, orders.order_id
FROM customers
CROSS JOIN orders;A self join is a regular join but the table is joined with itself.
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;NULL values represent missing or unknown data. Proper handling of NULL values is essential for accurate queries.
SELECT customers.name
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id
WHERE orders.order_id IS NULL;The `IS NULL` and `IS NOT NULL` operators are used to test for NULL values.
SELECT order_id
FROM orders
WHERE customer_id IS NULL;SELECT name
FROM customers
WHERE email IS NOT NULL;Temporary tables are used to store intermediate results temporarily during a session.
CREATE TEMPORARY TABLE temp_sales AS
SELECT customer_id, SUM(order_amount) AS total_sales
FROM orders
GROUP BY customer_id;CTEs create temporary result sets that can be referenced within a `SELECT`, `INSERT`, `UPDATE`, or `DELETE` statement.
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 CTEs are used to work with hierarchical data, such as organizational charts or folder structures.
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 perform calculations across a set of table rows related to the current row.
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 encapsulate SQL code for reuse and can include logic and control-of-flow constructs.
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 automatically execute SQL code in response to certain events on a 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;UDFs allow you to create custom functions to perform operations not covered by built-in functions.
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;The event scheduler allows you to automate tasks to run at specified times or intervals.
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 can improve performance and manageability by dividing a large table into smaller, more manageable pieces.
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 provide instructions to the optimizer to influence the execution plan of a query.
SELECT /*+ MAX_EXECUTION_TIME(1000) */ *
FROM orders
WHERE order_amount > 100;Virtual columns are computed based on other columns and do not store the data physically.
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 enables efficient text searching within MySQL.
CREATE FULLTEXT INDEX idx_description ON products(description);
SELECT * FROM products
WHERE MATCH(description) AGAINST('search term');MySQL supports spatial data types for geographic information systems (GIS).
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;Indexes improve the speed of data retrieval operations by providing a quick way to look up rows.
CREATE INDEX idx_email ON customers(email);Optimizing queries involves using best practices and tools to make SQL queries run faster.
EXPLAIN SELECT * FROM orders WHERE order_date > '2023-01-01';Caching stores frequently accessed data in memory for quicker retrieval.
SET GLOBAL query_cache_size = 1048576;
SET GLOBAL query_cache_type = 1;Normalization organizes data to reduce redundancy and improve data integrity.
-- 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)
);Securing data involves protecting it from unauthorized access and ensuring privacy.
GRANT SELECT, INSERT ON database_name.* TO 'username'@'host' IDENTIFIED BY 'password';Data encryption ensures that data is protected during transmission and storage.
-- 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.pemRegular backups ensure data can be recovered in case of a failure.
mysqldump -u username -p database_name > backup_file.sqlMonitoring and profiling tools help track database performance and identify bottlenecks.
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2;