0% found this document useful (0 votes)
72 views

PHP Couse Referance

The document provides an overview of PHP course content covering various PHP concepts like data types, constants, logical operators, error control operators, loops, arrays, functions, and array methods. It discusses getting the type of variables, defining constants, arithmetic, logical, and error control operators. It also covers for, foreach, do-while loops, and looping through indexed and associative arrays. Methods like in_array(), array_search(), array_key_exists() and adding items to arrays using array_push() are demonstrated. Functions and passing parameters, returning values, and framing output is explained. Finally, it shows multi-dimensional arrays and looping through them.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views

PHP Couse Referance

The document provides an overview of PHP course content covering various PHP concepts like data types, constants, logical operators, error control operators, loops, arrays, functions, and array methods. It discusses getting the type of variables, defining constants, arithmetic, logical, and error control operators. It also covers for, foreach, do-while loops, and looping through indexed and associative arrays. Methods like in_array(), array_search(), array_key_exists() and adding items to arrays using array_push() are demonstrated. Functions and passing parameters, returning values, and framing output is explained. Finally, it shows multi-dimensional arrays and looping through them.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 58

/* PHP cousre content

***/

1- data types :

a : gettype($var1); // get the type of the var1


:String - integer - float - double

ex :
<?php

$var1 = 'amr'; // string


$var2 = [1,2,3]; // array
$var3 = 12; // integer
$var4= 1.2; // float
$var5 = false; // boolen
$var6 = null; // null
$var7 = new car(); // object
$var8 = fopen('amr.text', 'r') ; // resourse

class car {
function carWalk(){
$this->wheel= "mechlin";
}
}

echo "<h2> get type </h2>";

echo gettype($var1)."<br/>";
echo gettype($var2) ."<br/>";
echo gettype($var3) ."<br/>";
echo gettype($var4) ."<br/>";
echo gettype($var5) ."<br/>";
echo gettype($var6) ."<br/>";
echo gettype($var7) ."<br/>";
echo gettype($var8) ."<br/>";

echo "<h2>var_dumb</h2>";

var_dump ($var1);
var_dump ($var2) ;
var_dump ($var3) ;
var_dump ($var4) ;
var_dump ($var5) ;
var_dump ($var6) ;
var_dump ($var7) ;
var_dump ($var8) ;
?>

/
**=================================================================================
========================*/
2- constats // Global

syntax : define(Name, value , case senstive)


case senstive : true or false:default .
true:- means igore case .
fasle :- means don't igonre case .
================================================================
ex:
define("FISRT_NAME", "amr",fasle) ;
echo FISRT_name ;
====>'Not defined '
=================================================================
define("FISRT_NAME", "amr",true) ;
echo FISRT_name ;
====>'amr'

echo PHP_INT_MAX ; // constatnt bulit in in the langauge


9223372036854775807

__ // magic constats :

echo __FILE__ . '<br>' ; C:\xampp\htdocs\php_course\index.php // CURRENT


FILE
echo __DIR__ . '<br>' ; C:\xampp\htdocs\php_course //CUURENT
DIRECTORY
echo __lINE__ . '<br>' ; 10 //CURRENT
LINE

===================================================================================
=============================

$z= $x**$Y ; // aritmatice opertaor power .


===================================================================================
==============================

3- logical opertaor :
[and] : condition 1 and 2 and 3
[&&] : same as and but it preferable .
[xor] : one is true [lazem shart wa7ed yt772 bas msh el etneen ]
[||] : or
[or] : condition1 or condition 2 or all
[!] : not

===================================================================================
================================

4 - error control opertaor : [@]

fopen('amr.txt', 'r') // open amr.txt file which not exists .

"Warning: fopen(amr.txt): failed to open stream: No such file or directory in C:\


xampp\htdocs\php_course\index.php on line 3"

// if we want to igonre error and disaper from hackers (file path) : put(@) :
before function.
@fopen('amr.txt', 'r')

//if we want to put custom message when the page is not exists:
@fopen('amr.txt', 'r') or die(' this File is not found please go another page') .

//we can use this method in including files :


( @include('myFile.php') ) or die('not found !!!') ;
===================================================================================
====
for loop:
$lang = ['arabic0', 'eng', 'frensh', ' german', 'china'];
for($i= 0 ; $i<= count($lang); $i++) {
echo $lang[$i] . "<br>";
}

// advanced loop :
1-
for($i= 1 ; ; $i++) {
if($i > 20) break ;
echo $i . "<br>";
}

2-

$i= 1 ;
for(;; $i++) {
if($i > 20) break ;
echo $i . "<br>";
}

3-

$i= 1 ;
for(;;) {
if($i > 20) break ;
echo $i . "<br>";
$i++ ;
}

=================================================
do-while :

$i= 100;
do {
$i++ ;
echo $i ;
}while ($i<20);
===========================================================================

for each (): looping on array :

$cot = array(
'egy' =>'egypt',
'leb' =>'lebnaon',
'sy' =>'syria',
'u' =>'usa',
'ca' =>'canada',
'sau' =>'sudia aribia',
'qa' =>'qatar'
);
foreach($cot as $key => $value ){
echo $key . ":" . $value .'<br>';
}
"egy:egypt
leb:lebnaon
sy:syria
u:usa
ca:canada
sau:sudia aribia
qa:qatar"

===================================================================================
===
functions advanced :

<?php

function getTicker($user , $age ){


$ticket = rand(1000,1500000);
if($age >= 30){
$msg = 'your name is '. $user . "and your age is : " . $age .'<br>' ;
$msg .= 'you are qualified to get the ticket congrats '.'<br>';
$msg .= 'ur ticket ID is '.'<span>'. $ticket.'</span>' ;
}else {
$msg = 'your name is '. $user . "and your age is : " . $age .'<br>' ;
$msg .= 'you are not qualified to get the ticket sorry '.'<br>';
}
return $msg ;
}
$id= getTicker('amr', 20);

// frame styling
function cerateFrame($element){
$frame = "<div class= 'frame'>";
$frame .= $element ;
$frame .= "</div>";
return $frame ;
}

$myElement = cerateFrame($id)
?>

<!DOCTYPE html>
<html>
<head>
<title>content</title>
<style>
.frame{
background-color: #ccc ;
color: white ;
padding :20px ;
margin: auto ;
text-align : center ;
width : 400px ;
border-radius : 10px ;
}
</style>
</head>
<body>
<?php echo $myElement ?>
</body>
</html>
<head></head>
===================================================================================
====================+
indexed array :
foreach loop on array :

$langs = ['html', 'css', 'js', 'java', 'bootstrap', 'hquery', 'ajax', 'jason'];


$langs[]= 'amr'; // add value to array
$langs[5] = 'karreem'; // reset index 7
echo "<ul>";
foreach($langs as $value){ // key as value
echo '<li>'. $value . '</li>' ;
}
echo "</ul>";

echo count($langs); // length of array in php


'9'

===========================================================
for loop on array :

for($i = 0 ; $i <= count($langs); $i++){ // key as value


echo '<li>'. $langs[$i]. '</li>' ;
}
===================================================================================
==========

associative array :
foreach():
syntax :
["key" => 'value ,
"key" => 'value,
"key" => 'value
]

note ! :
key : accpets only integer and string not array or object

ex :

<?php

$langs = [
'html' => "60%",
'css' => "60%",
'js' => "40%",
'java' => "20%",
'bootstrap' => "20%",
'hquery' => "70%",
'ajax' => "20%",
'jason' => "90%"
];
$langs[]= 'amr'; // add value to array
$langs[5] = 'karreem'; // reset index 7
echo "<ul>";
foreach($langs as $key => $value){ // key as value
echo '<li>'. $key. ' '. $value . '</li>' ;
}
echo "</ul>";
echo count($langs); // length of array in php
?>

note : key must be unique : css , html : if we asign many values it takes last one
==============================================================

multi dimention array :

$diet = array(
"dayOne" => array('meat', 'bread', 'banaana', 'apple', 'kewi') ,
"dayTwo" => array('bread', 'strawibey', 'apple') ,
"dayThree" => array('milk', 'fish', 'banaana', 'meat', 'kewi') ,
"dayFour" => array('meat', 'bread', 'banaana', 'apple', 'kewi',
array(
" dayFive" => array('meat', 'bread', 'banaana', 'apple', 'kewi')
))
);
echo"<pre>";
print_r($diet) ;
echo $diet["dayFour"][6]['meat'] ;
echo "</pre";

looping in associative array :

$diet = array(
"dayOne" => ['meat', 'bread', 'banaana', 'apple', 'kewi'],
"dayTwo" => array('bread', 'strawibey', 'apple') ,
"dayThree" => array('milk', 'fish', 'banaana', 'meat', 'kewi') ,
"dayFour" => array('meat', 'bread', 'banaana', 'apple', 'kewi',
array(
" dayFive" => array('meat', 'bread', 'banaana', 'apple', 'kewi')
))
);
echo"<pre>";
print_r($diet) ;

foreach($diet as $day => $food) {


echo "<h3> in ". $day . " i will eat </h3>" ;
foreach($food as $items) {
echo '-' . $items . '<br>';
}
}
echo "</pre>";

output :

in dayOne i will eat


1 -meat
2 -bread
3 -banaana
4 -apple
5 -kewi
in dayTwo i will eat
6 -bread
7 -strawibey
8 -apple
in dayThree i will eat
9 -milk
10 -fish
11 -banaana
12 -meat
13 -kewi
in dayFour i will eat
14 -meat
15 -bread
16 -banaana
17 -apple
18 -kewi
======================================================================

array methods :

$array = [
'html',
'css',
'php' ,
'js' ,
'mysql' ,
'ruby',
'python'
] ;

1 - in_ array : - // check if it's exits in in the array

function : in_array(needle, hystack, type )

if(in_array('amr', $array ,true )){


echo 'yes its exist';
}
true : means identical in data type .
==============================================
2 - array_search :
function : array_search(needle, hystack, type )

$search = array_search('css', $array , true);


echo 'yes its found in index '. $search;

====> "yes its found in index 1" .

==============================================

3- array_key_exists(needle , hystack) // search in array associative or indexed

if(array_key_exists("html", $array)){ // 'html is a key


echo 'yes its found ';
}

if(array_key_exists("html", $array)){
echo 'yes its found ';
}else {
echo 'no' ;
}
'no' : because it's not key but if we add in associative array : yes its found .

if(array_key_exists(2, $array)){ // index


echo 'yes its found ' . $array[2];
}else {
echo 'no' ;
}
'yes its found php'
===============================================================================
add items to array :

1 - array_push (array , value1, value 2 , value N) // add elements to end of the


array .

array_push($array , 'amr' , 'kareem');


echo '<pre>';
print_r($array);
echo '<

$array = [
'html',
'css',
'php' ,
'js' ,
'mysql' ,
'ruby',
'python'
] ;

Array
(
[0] => html
[1] => css
[2] => php
[3] => js
[4] => mysql
[5] => ruby
[6] => python
[7] => amr
[8] => kareem
)

===========================================

array_unshift() // add element to start of the array .

array_unshift($array , 'amr' , 'kareem');


echo '<pre>';
print_r($array);
echo '</pre>';

Array
(
[0] => amr
[1] => kareem
[2] => html
[3] => css
[4] => php
[5] => js
[6] => mysql
[7] => ruby
[8] => python
)

=======================================================
deleting array :
1 - array_pop(array) //delete the last element in the array .

array_pop($array);
echo '<pre>';
print_r($array);
echo '</pre>';
?>

Array
(
[0] => html
[1] => css
[2] => php
[3] => js
[4] => mysql
[5] => ruby
)

======================================

2- array_shift : delete the first element in the Array .

array_shift($array);
echo '<pre>';
print_r($array);
echo '</pre>';
?>

Array
(
[0] => css
[1] => php
[2] => js
[3] => mysql
[4] => ruby
[5] => python
)

================================================================================

sort indexed Array :

sort(array , sortting type) // sort string array alphapitical .

sort($array);
echo '<pre>';
print_r($array);
echo '</pre>';
============================
methods of sort :

sort($array, SORT_STRING); // treat numbers as string : from A to Z

Array
(
[0] => 10
[1] => 20
[2] => ass
[3] => html
[4] => js
[5] => mysql
[6] => php
[7] => python
[8] => ruby
)
============================
rsort() : //reverse sort from Z to A

rsort($array, SORT_STRING);

===================================================================================
=====================

2 - sort associative array :

1 - asort(array , sorting type) : // sort associative array from A to Z


alphapitical

$array = [
"ass" => 80 ,
"php" => 20 ,
"js" => 10 , /// sort the value not the key
"mysql" => 50 ,
"ruby" => 70 ,
"python" => 60
] ;

asort($array, SORT_STRING);
echo '<pre>';
print_r($array);
echo '</pre>';

so the resuly :

Array
(
[js] => 10
[php] => 20
[mysql] => 50
[python] => 60 // sort value for smaller to bigger
[ruby] => 70
[ass] => 80
)

=================================
2- arsort () // sort the value in reverse in associative array from bigger to
smaller alphapitical:

arsort($array, SORT_STRING);
Array
(
[ass] => 80
[ruby] => 70
[python] => 60
[mysql] => 50
[php] => 20
[js] => 10
)
=========================

to sort the key in associative array :

1- ksort() sort the key from A to Z alphapitical : //key sort

ksort($array, SORT_STRING);

Array
(
[ass] => 80
[js] => 10
[mysql] => 50
[php] => 20
[python] => 60
[ruby] => 70
)
=================

2- krsort() : // key reversed sort alphapitical .

krsort($array, SORT_STRING);

Array
(
[ruby] => 70
[python] => 60
[php] => 20
[mysql] => 50
[js] => 10
[ass] => 80
)

=========================================

array_reverse( array , peserve ) : // arrange array from last one to first one
preserve : true or fasle
true : preserve the index of the last one as its 5 it goes to the first line with
index

$array = [
"ass" ,
"php" ,
"js" ,
"mysql" ,
"ruby" ,
"python"
] ;

$reversedAray = array_reverse($array);
echo '<pre>';
print_r($reversedAray);
echo '</pre>';
result :
when preserve its fasle : array_reverse($array, fasle ) // default value
Array
(
[0] => python
[1] => ruby
[2] => mysql
[3] => js
[4] => php
[5] => ass
)
but when it is true : array_reverse($array, true ) //preserve the index value

Array
(
[5] => python
[4] => ruby
[3] => mysql
[2] => js
[1] => php
[0] => ass
)

// preserve the index 5 in the first one


===========================================================

2 - shuffle(array)

shuffle($array); // each reload random the arrangent of the array

Array
(
[0] => php
[1] => mysql
[2] => ass // random
[3] => ruby
[4] => python
[5] => js
)
===================================================================

array_fill(index , number , value) : //used to fill array by value

$fill = array_fill(2 , 10, 'amr');


echo '<pre>';
print_r($fill);
echo '</pre>';

result :

Array
(
[2] => amr
[3] => amr
[4] => amr
[5] => amr
[6] => amr
[7] => amr
[8] => amr
[9] => amr
[10] => amr
[11] => amr
)

==================
filling by multi dimention array :

$fill = array_fill(1 , 5, [
'amr' ,
'mohamed',
'kareem' ,
'hossam'
]
);
echo '<pre>';
print_r($fill);
echo '</pre>';

result :

Array
(
[1] => Array
(
[0] => amr
[1] => mohamed
[2] => kareem
[3] => hossam
)

[2] => Array


(
[0] => amr
[1] => mohamed
[2] => kareem
[3] => hossam
)

[3] => Array


(
[0] => amr
[1] => mohamed
[2] => kareem
[3] => hossam
)

[4] => Array


(
[0] => amr
[1] => mohamed
[2] => kareem
[3] => hossam
)

[5] => Array


(
[0] => amr
[1] => mohamed
[2] => kareem
[3] => hossam
)

========================
=============================================================

array_sum(array) : //sumtion of all values inside array

$arr = [1 , 2 , 3 , 4 , 5 , 'amr'] ; //ignore string value


$sum = array_sum($arr) ;

echo '<pre>';
print_r($array);
echo '</pre>';
echo $sum ;

result :

Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => amr
)
15
==========================

array_rand(array , number of elemnts u wnat) //get a random elements from my


array /

"ass" ,
"php" ,
"js" ,
"mysql" ,
"ruby" ,
"python"
] ;

$rand = array_rand($array, 3) ;

echo '<pre>';
print_r($array);
echo '</pre>';
echo $array[$rand[0]] . "<br>";
echo $array[$rand[1]] ."<br>";
echo $array[$rand[1]] ."<br>";

result :

Array
(
[0] => ass
[1] => php
[2] => js
[3] => mysql
[4] => ruby
[5] => python
)
ass
mysql
mysql

'randomly in every reload'

===============================================

array_unique(array , sorting type , ) //remove the repated elements in the array


.

$array = [
"ass" ,
"php" ,
"js" ,
"js" ,
"mysql" ,
"ruby" ,
"python" ,
"python" ,
"ruby" ,
"mysql"
] ;

$unique = array_unique($array) ;

echo '<pre>';
print_r($array);
echo '</pre>';

echo '<pre>';
print_r($unique);
echo '</pre>';

result :

Array
(
[0] => ass
[1] => php
[2] => js
[3] => js
[4] => mysql
[5] => ruby
[6] => python
[7] => python
[8] => ruby
[9] => mysql
)
Array
(
[0] => ass
[1] => php
[2] => js // it removes the
repated elements in the top array
[4] => mysql
[5] => ruby
[6] => python
)

===================================================================================
=============================================================

2- String :
=============

1 - explode(seprator, string, limit) //cuts the string and convert it into


array .

// seprator means the point in which i will cut the string

$myString = 'l love php' ;


$myExplodedeString = explode( " ", $myString ) ;
echo "<pre>";
print_r($myExplodedeString);
echo "</pre>";

result :
Array
(
[0] => l
[1] => love
[2] => php
)

// here it cuts form the space between the string

but here it cuts from the slash or any symbol:

============
$myString = 'l-love php' ;
$myExplodedeString = explode( "-", $myString ) ;

result :
Array
(
[0] => l
[1] => love php
)
ex : 2 .

$myString = 'l,love, php ,too, much' ;


$myExplodedeString = explode( ",", $myString , 2) ; //max limit 2
echo "<pre>";
print_r($myExplodedeString);
echo "</pre>";

result :
Array
(
[0] => l
[1] => love, php too much
)

ex : 2 with negative value remove the last elements according to the last
negative index number

$myExplodedeString = explode( ",", $myString , -1) ;

Array
(
[0] => l
[1] => love
[2] => php
[3] => too
) // removed the last elements which is 'much'

$myExplodedeString = explode( ",", $myString , -3)


Array
(
[0] => l
[1] => love
)
// removed the last three elements which is 'much , too , php'

ex: 3 with limit zero :


$myExplodedeString = explode( ",", $myString , 0) ;
Array
(
[0] => l,love, php ,too ,much //on the same line with index 0
)

=========================================================================
real life example [i want to add link by writing css files ]

$myString = 'widget, clock,coloring , index' ;


$myExplodedeString = explode( ",", $myString , 3) ;
echo "<pre>";
print_r($myExplodedeString);
echo "</pre>";

for($i=0 ; $i<= count($myExplodedeString) ; $i++) {


echo "<link rel='stylesheet' href='css/" . $myExplodedeString[$i] . ".css'>";

//css files will be added in web page

===================================================================================
====

implode(seprator , array) : convert array to string :


, join(seprator ,array). // el esm el most3ar le implode

ex :
$array = array('amr', 'mamoud' , 'mohamed' , 'saker') ;
$str = implode(" & ", $array ) ;
echo ' hello our clients are :' . $str ;

result :" hello our clients are :amr & mamoud & mohamed & saker" //stringed .

===========================================================

str_split(string , length , ) // split string and put it intio array

$str = 'hello o live php' ;


echo $str .'<br>' ;

echo "<pre>" ;
$arr = str_split($str) ;
print_r($arr) ;
echo "</pre>" ;

result :

hello o live php


Array
(
[0] => h
[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => o
[7] =>
[8] => l
[9] => i
[10] => v
[11] => e
[12] =>
[13] => p
[14] => h
[15] => p
)

=============

// if length = 2 it take 2 words :

$arr = str_split($str, 2) ;

Array
(
[0] => he
[1] => ll
[2] => o // space
[3] => o //space
[4] => li
[5] => ve
[6] => p
[7] => hp
)
==============================================

chunk_split(string, length[default value = 76] ,End[default value \r\n] ) :

$arr = chunk_split($str, 2 , " @ ") ;


echo $arr ;
result :

hello o live php


he @ ll @ o @ o @ li @ ve @ p @ hp @ /// small pices according to number of
length and End vlue is symbol

================================================

str_repeat(string , repate ) : // repeat the string :

$str = 'hello ' ;


echo $str .'<br>' ;

$arr = str_repeat($str, 20) ;


echo $arr ;

result :

hello
hello hello hello hello hello hello hello hello hello hello hello hello hello hello
hello hello hello hello hello hello // 20 times

================================]

str_shuffle(string) : //randomize words in a string in every reload

$str = 'hello ' ;


$arr = str_shuffle($str) ;
echo $arr ;

loehl , lhloe , e hlol ,l lhoe ///mainly used toi genrate keys or tokkens

==========================================

strlen($string) : /// calculate the length of a string

$str = 'hello ' ;


$arr = strlen($str) ;
echo $arr ;

"6"
======================================+

addslashes(string) : // esacape the qouts because security in database

$str = " i will go at six o'clcok ";


echo $str . "</br>";

$skipped = addslashes($str) ;
echo $skipped ;
result :

"
i will go at six o'clcok
i will go at six o\'clcok // added esacape charchter : used to clean a string
and display infront of the user

"

=====================

stripslashes(string) : //oposite of addslashes (clean slashes from string)

$str = " i will go at six o'clcok ";


echo $str . "</br>";

$skipped = addslashes($str) ;
echo $skipped . "</br>";

$cleanedAfterDatabase = stripslashes($skipped);
echo $cleanedAfterDatabase ;

result :

$str = " i will go at six o'clcok ";


echo $str . "</br>";

$skipped = addslashes($str) ;
echo $skipped . "</br>";

$cleanedAfterDatabase = stripslashes($skipped);
echo $cleanedAfterDatabase ;

============================================

striptags(string , allow ) : // remove all html tags from string like links

$str = " i love <span> php </span> go to link <a href = 'my.html '>goggle</a> to
learn php ";
echo $str . "</br>";

$strippedTages = strip_tags($str) ;
echo $strippedTages ;

result :

i love php go to link goggle to learn php // underllined link


i love php go to link goggle to learn php // removed link underllined used in
security

===============

strip_tags with allow : strip_tags(string , allow) : // alow the tags that i want :

$strippedTages = strip_tags($str, "<span>") ;


result :
i love php go to link goggle to learn php // leaved the span in document
================================================================================

strtolower(string) : // to lower case

$str = " HELLO ";


echo $str . "</br>";

$capitalized = strtolower($str);
echo $capitalized ;

result :

"HELLO
hello"
=======================

2- strtoupper(string) : // oposite of strtolower() ;

==========================================

3- lcfirst(string) : // Make the first letter small // lowerCase first

$str = "Hello i Hove php";


echo $str . "</br>";

$capitalized = lcfirst($str);
echo $capitalized ;

=============

ucfirst(string) : // oposite of lcfirst()

$capitalized = ucfirst($str);

==================================

trim(string, charlist[optional]), trimleft() , trimright() :

\0 null ,
\n newline
\t tab
\r carriege return ,
\x0B vertical tab
" " space

ex :
$str = "hello i Hove php";
echo $str . "</br>";

echo var_dump($str) .'</br>';

$str = " hello i Hove php ";


echo var_dump($str) .'</br>';
$trimmed = trim($str);
echo $trimmed .'</br>';
echo var_dump($trimmed) .'</br>';

hello i Hove php


string(16) "hello i Hove php"
string(26) " hello i Hove php "
hello i Hove php
string(16) "hello i Hove php"
======================================

ltrim() // trim grom left


rtrim() //trim from right
=====================================
// trim with soecific value
$str = "hello i Hove php";
echo $str . "</br>";

$trimmed = trim($str , 'he');

echo $trimmed ;

result :
hello i Hove php
llo i Hove php

===================================================
str_word_count(string , 0[default] or 1[return indexed array] , 2[returns
associative array] , charchter is counted in stringlike[&] ) ;

$str = "hello i Hove php";


echo $str . "</br>";
$count = str_word_count($str, 0);
print_r($count) ;

result :
hello i Hove php
4 // number of words of the wstring

$count = str_word_count($str , 1);

Array ( [0] => hello [1] => i [2] => Hove [3] => php )

===========================================================

2 : returns associative array :


$count = str_word_count($str , 2);

echo "<pre>";
print_r($count) ;
echo "</pre>";

hello i Hove php


Array
(
[0] => hello // the key is the index of the word hello and the value is
hello
[6] => i
[8] => Hove
[13] => php
)

=============================================
analayiz rhe link as variables
$str = "name='amr'&age'23'address='elshek ";

$count = parse_str($str);
echo $name ;
echo $age ;
echo $address ;

result :
'amr'
'23'
'elshek'

=========================================

// if i want to put hte resulted string in array add second parameter :

parse_str(string ,array) :

ex :

$str = "name='amr'&age='23'&address='elshek'";

$count = parse_str($str, $array);

echo "<pre>" ;
print_r($array);
echo "</pre>" ;

result :

Array
(
[name] => 'amr'
[age] => '23'
[address] => 'elshek'
)

========================================================

nl2br(string, Xhtml) : // new line to break <br> // change the \n to <br>

$str = " hello i love php very \n much ";


echo $str
echo nl2br($str);

result :

hello i love php very much hello i love php very


much "

=========================================================
1- strpos(string, the word i want to search , the starting index i want to search
from)

$str = " hello i love php very \n much ";


echo $str ;
echo strpos($str, "very", 0);

result :
18 : the index of "very"

2- stripos(): //case insenstive // search incase of capital or small

3- strrpos() : // strinf right postion //search from right


4- strripos() : // strinf right postion and case insenstive //search from right

$str = " hello i love php very much very ";

echo strrpos($str, "very", -2); // negative count from right

=======================================

strstr(string, search ,beforsearch[optional]) : //search the word with after


words only or befor only //important

ex :

$str = "[email protected]". "<br>";


echo $str;
echo strstr($str,'@');
echo strstr($str,'@', false); // get the all words before "@"
echo strstr($str,'@', true); //defalut : get the all words after "@"

result :
@gmail.com // default with no third parameter
@gmail.com // all words after @
amrmohsen72 // // all words before @

2- echo stristr($str,'@'); search igonre insenstive

===================================================================================
====

strcmp(string1 ,string2) // string compare

results :
[0] : means string1 = string2 ,

ex 1: [string1 = string2]

$str1 = "helloooo" ;
$str2= "hello";
echo strcmp($str1, $str2);

result: 0

ex: 2

$str1 = "helloooo0000000000" ;
$str2= "hello";
echo strcmp($str1, $str2);

result: 13 //string1 > string2 by 13 charchters

ex : 3
$str1 ="hello" ;
$str2= "helloooo0000000000" ;

echo strcmp($str1, $str2);


-13 // string2 > string1 by 13
==========================================================

strcmp(string1 ,string2, number) string compare the four of first three numbers

$str1 ="PHPPPPPPPP" ;
$str2= "PHP" ;

echo strncmp($str1, $str2, 4);


result : 1 // means that copmares from first four numbers

====================================================
stringrev(string) : /// reverse the string words

$str1 ="amr" ;
echo strrev($str1);

result :
"rma"

=========================================
substr(string[req], start[req], length [optional]) : // subract string

ex :
$str1 ="i love php so much" ;
$pice = substr($str1,7) ;
echo $pice ;

result :
"php so much"

ex : 2 //with length parameter which is length of cuuting

$str1 ="i love php so much" ;


$pice = substr($str1,7,3) ;
echo $pice ;
"php"
==============
substr() with negative value : /search from lasst element(right) :

ex:
$str1 ="i love php so much" ;
$pice = substr($str1,-6,3) ; 3 : number of piece
echo $pice ;
"o m"
==================

length with negative value : // all from right


$str1 ="i love php so m uch" ;
$pice = substr($str1,-3,-2) ;
echo $pice ;
================================

substr_count(string ,substring , start ,length) :

$str1 ="i love php so much i love php so much" ;


$pice = substr_count($str1, " php") ;
echo $pice ;

result: "2" // the repated number o php text in the sentence

ex : 3

$str1 ="i love php so much i love php so much php php " ;
$pice = substr_count($str1, " php", 1 ) ;

result : " 4 " // start search from count for "php" words in string

ex : 4
$pice = substr_count($str1, " php", 1 , 30) ;

result: "2"

======================================================

substr_compare(string1 , string2 , start postion , length , case senstive ) :

// copmare the firsst letter in word according to alphapitical order .

ex: 1

$str1 ="zmr" ;
$str2 = "osama";
$copmare = substr_compare($str1 , $str2 ,0 );
echo $copmare ;

result : 1 // str1 > str2 in(z > o in alphapitical)


--------------------------
$str1 ="heloo osama" ;
$str2 = "osama";
$copmare = substr_compare($str1 , $str2 ,0 );
echo $copmare ;

result = -1 // str2 > str1 in(o > h in alphapitical)


----------------------------

$str1 ="heloo osama" ;


$str2 = "osama";
$copmare = substr_compare($str1 , $str2 , 6);

result : 0 // str1 = str2 where it starts form 6 index and compare (osama with
osama)
---------------------

$str1 ="heloo osama" ;


$str2 = "os";
$copmare = substr_compare($str1 , $str2 , 6);
result : osama > os by 3 letters (copmareing)
-----------------------------------
length:

$str1 ="heloo osamaamr" ;


$str2 = "os";
$copmare = substr_compare($str1 , $str2 , 6, 5);

result : 3 // osamaamr > os when havig 5 length[osama] by three

=============================================

include , include_once : /// include pages in mya page -

include "inc.php" ;
include_once "inc.php" ;

================================
require , require_once : //same as include but if theres no files it stop the
script
==========================================================

FILE system :
--------------
dirname() : //get the path of the file

echo dirname(__FILE__);
$file = 'amr.txt';

result : C:\xampp\htdocs\php_course
------------------
ex : 1

echo dirname(__FILE__);

$file = 'amr.txt';
if(file_exists($file)) {
echo "good ['. $file.'] is fonund" ;
file_put_contents($file, "add with php"); // it will write the following
inside the file
}
}
else {
echo " sorry ['. $file.'] is Not fonund" ;
}

result : sorry ['. amr.txt.'] is Not fonund

// if the file is not found the function file_put_contents() will create it .

echo " sorry ['. $file.'] is Not fonund but o cerated it with php" ;
file_put_contents($file, "add with php"); /// create flie if not exists

=========================================
is_writable() : // able to write inside it not read Only
if(is_writable($file)) {
echo " good ['. $file.'] is writable" ;
}
========================================

mkdir() // create a folder


rmdir() // remover a folder
is_dir() // check is folder

ex : 1

$name = 'amr';
if(is_dir($name)) { // if folder already exists
rmdir($name) ;
echo 'the directory' . $name . 'is derated ' ;
}
else{
echo " no files here";
}
"no files here"
----------------------

$name = 'mohsen';
if(is_dir($name)) {
echo " file already existes";
}
else{

mkdir($name) ; //if files is not exits create it


echo 'the directory' . $name . 'is cerated ' ;
}
---==================================

dirname('path') : // directory name or folder name

echo __FILE__ ;
result " C:\xampp\htdocs\php_course\index.php "
-------------
echo dirname(__FILE__);
result : "C:\xampp\htdocs\php_course "

-================
ex ;

include dirname(__FILE__). "/mohsen/in/test.php"; // C:\xampp\htdocs\


php_course/mohsen/in/test.php

"text from includssde"


==============
note : dirname(__FILE__) = __DIR__ // in php5

==================================

basename(path , suffex) :

echo basename(__FILE__ ) // get the name of m file


result : "index.php"

----
echo basename(__FILE__ , '.php') // the second parameter is the word that i
want to remove like profiles

result : "index' .
============

advanced example : // so easy

if(file_exists(__DIR__ . '/PHP')) { // check if the dri is exits


echo "this directory is exitis " ;
} else {
mkdir(__DIR__ . '/PHP'); // make the directory
}

$directory = __DIR__ . "/PHP/"; // assign directory to variables


file_put_contents($directory . "text.php", "heloo world");

$myfile = $directory . "text.php" ;


chmod($myfile , 0444) ; // 0444 : read only mode

if(is_writable($myfile)) { // check if the file is writable


file_put_contents($myfile , "my write");
} else {
chmod($myfile , 0755); // change mode to writeable
file_put_contents($myfile , '<?php echo "congrats !!" ?>' );
}

include $myfile ; // include the file that i have been created to my page

========================================================

file_put_contents(file , data , mode , context )


mode :

FILE_APPEND : // use to add content without removing the old content


LOCK_EX : // used to not make many person write at the same time
FLIE_USE_INCLUDE_PATH

ex :
file_put_contents("amr.text" , "this created by php" , FILE_APPEND) ; //
add over old and dont delete it .
file_put_contents("amr.text" , "this created by php" , LOCK_EX) ; //
lcok file not other users
file_put_contents("amr.text" , "this created by php" , LOCK_EX | FILE_APPEND) ;
// use two together

===================================================================================
==========================================
copy(oldefile , newfile ) ;
copy("amr.txt" , "amr_new.txt") ;

function to make backup file : -

function copyMe($extionsion) {
$orginal = __FILE__ ;
return copy($orginal, $orginal . '.' . $extionsion );
}
copyMe("cool");
======================================
rename(oldname, newname) :

// used to rename file to other name also it can move it to other directory

1- use it to only rename file


rename("amr.txt",file.txt");

2- use it to move file in a folder and aslo rename it

mkdir("profile");
rename("amr.txt", __DIR__ . "/profile/file.txt");

============================================================================
pathinfo(path , options) ;

echo "<pre>";
print_r( pathinfo(__FILE__));
echo "</pre>";

result : array
Array
(
[dirname] => C:\xampp\htdocs\php_course
[basename] => index.php
[extension] => php
[filename] => index
)

// if i want to prrint any properties of path write it in the second parameter

print_r( pathinfo(__FILE__ , PATHINFO_DIRNAME));


result : "C:\xampp\htdocs\php_course "

--------
$links = pathinfo(__FILE__ );
echo $links["extension"];

result : "php"
====================================

unlink(filename , context ) , // used to delete the entire file

unlink(__DIR__ ."/profile/file.txt");

ex : // very easy

$myFile = __DIR__ ."/profile/file.txt" ;


if( file_exists($myFile) && is_writable($myFile)){
unlink($myFile);
echo "file deleted!" ;
}else {
if(file_exists($myFile)) {
echo "the file is unwriteble and cant deletes it";
chmod($myFile , 0777);
}
}
===============================
rmdir() / remove the directory[file] ;
rmdir('profile');

========================================================

scandir(dir, sort ,context ) /scan the folders inside the file

ex :
$myFolder = __DIR__ . '/amr' ;
$file = scandir($myFolder);
echo "<pre>";
print_r($file) ;
echo "</pre>";

result : // array of files of my folders

Array
(
[0] => .
[1] => ..
[2] => acsses.accdb
[3] => amr.txt
[4] => exel.xlsx
[5] => publis.pub
[6] => rar.zip
)
--------------
// use sort methods :

1- SCANDIR_SORT_DESCENDING // descinding
$myFolder = __DIR__ . '/amr' ;
$file = scandir($myFolder , SCANDIR_SORT_DESCENDING);
echo "<pre>";
print_r($file) ;
echo "</pre>";

result :

Array
(
[0] => rar.zip
[1] => publis.pub
[2] => exel.xlsx
[3] => amr.txt
[4] => acsses.accdb
[5] => ..
[6] => .
)
----------------
3- use sort none

$file = scandir($myFolder , SCANDIR_SORT_NONE);

Array
(
[0] => .
[1] => ..
[2] => acsses.accdb
[3] => amr.txt
[4] => exel.xlsx
[5] => publis.pub
[6] => rar.zip
)

// defalut sort of files in the folder

---------------
rmdir($myFolder); // cant delete it because its not empty
Warning: rmdir(C:\xampp\htdocs\php_course/amr): Directory not empty in C:\xampp\
htdocs\php_course\index.php on line 10

// so if i want to delete it i will make a loop to

$myFolder = __DIR__ . '/amr' ;


$files = scandir($myFolder , SCANDIR_SORT_NONE);
echo "<pre>";
print_r($file) ;
echo "</pre>";

foreach($files as $file) {
if(is_file($myFolder . "/" . $file)) {
unlink($myFolder . "/" . $file) ;
}
} /// it will delete the all files inside the folder

===========================================================

fopen(filename , mode , include path , context )// open files

mode : // important !

r: read only starting from beginning of the file (file must be exist)
r+: read and write starting from beginning of the file (file must be exist)
w: write only (open and clear the content) (creat the file if not exist)
w+: write and read (open and clear the content) ( creat the file if not exist)
a: write only (open and write to the end of file) (creat the file if not exist)
a+ : write and read ( open and write to the end of file) (creat the file if not
exist)
x: write only (creat a new file) (file must not be exist or give error)
x+: write and read (creat a new file) (file must not be exist or give error)

note : handle line End

Unix : \n
Windows : \r\n
Mac :\R
===============================================================================

fread(handle ,length ) :

ex:
$handel = fopen("amrs.txt", "r");
$content = fread($handel , 34);
echo $content ;
result : hello iam amr mohsen from the file // from browser

$content = fread($handel , filesize('amrs.txt')); // function filesize() //


size of the file functionally
=============================================================================

fwrite(handle , string , length[optional] ) ;

$handle = fopen("amrs.txt", "r+");


$read = fread($handle , filesize('amrs.txt'));
echo "orginal " ."<br>" .$read ;
$write= fwrite($handle, "this is the new text"); //write inside the file

result : orginal
startthis is the new text
=======================================================

fseek(handle , offset[index] , whence) ;

whence :
1- SEEK_SET : // defalut start from beginning
2- SEEK_CUR : // seek cuurent : +number of index
3- SEEK_END : start from end negative value

ex :
1-SEEK_SET

$handle = fopen("amrs.txt", "r+");


fseek($handle , 4, SEEK_SET ); // i say write from index 4 of "elzero" ,
and then change index[4(r)] with "b";[cursour]
$write = fwrite($handle , "b");

result :
old: "elzero "
new : elzebo
-----------
ex: 2
$handle = fopen("amrs.txt", "r+");
fseek($handle , 4, SEEK_SET );
$write = fwrite($handle , "b");
fseek($handle , 1, SEEK_SET );
$write = fwrite($handle , "a"); // keyboaed cursor or pointer

result :
old: "elzero "
new : elzebo
new : eazebo

--------------------------
2- SEEK_CUR : // CURRENT pointer start search

ex :
$handle = fopen("amrs.txt", "r+");
fseek($handle , 2);
$write = fwrite($handle , "r");
fseek($handle , 2 ,SEEK_CUR);
$write = fwrite($handle , "h");
old : am*mo-sen
new: amrmo-sen
newest : amrmohsen
----------
$handle = fopen("amrs.txt", "r+");
fseek($handle , -4 ,SEEK_END); //searched from the end 4 steps[old
value(amrmo-sen) and repllace]
$write = fwrite($handle , "h");

result :
old : amrmo-sen
new : amrmohsen
==============================================================================

super Globals :

function amr() {
$name = "koko";
}
amr();
echo $name ;

Notice: Undefined variable: name in C:\xampp\htdocs\php_course\index.php on line 8

use Global :

$name = "koko";
function amr() {
echo $GLOBALS['name'] ;
}
amr();

result : koko
-------------------------
function amr() {
$GLOBALS['name'] = "koko";
}
amr();
echo $name;

result : "koko";
==================================================

prefined variables :

$_SERVER[] // server functions

echo $_SERVER["PHP_SELF"];
/php_course/index.php
-------------------------------
echo $_SERVER["SERVER_ADDR"]; //server ip address
::1
------------------------------------
echo $_SERVER["SERVER_NAME"];
localhost
------
if($_SERVER["SERVER_NAME"] == "localhost") {
echo 'you are from local host';
}
--------------------
echo $_SERVER["QUERY_STRING"]; // string after question mark in the link at
the top
name=amr&age=24
-----------------------
$_SERVER["HTTP_REFERER"] : // says what page i gat from used in traffic

echo "you get from the page :". $_SERVER["HTTP_REFERER"];


result : you get from the page :http://localhost/php_course/test.php
---------------------------

echo $_SERVER["SERVER_PORT"]; // port of the server


result: "80:
==========================================================
collecting data :

$_GET[] ;

index.php page :

<form action="test.php" method= "get">


<input type="text" name="username">
<input type="password" name= "password">
<input type="submit" name= "login">
---------
test.php page :

$admins = array("amr", 'osama' , 'mohamed');


$userName = $_GET["username"] ;
$passowrd = $_GET["password"];

if(in_array($userName , $admins)){
echo "welecome " . $userName . " to control panel";
}else {
echo "sorry this username isnot available";
}
=======================================
$_POST[] :

index.php page :

<form action="test.php" method= "post"> <!-- cant get the values in the link -->
<input type="text" name="username">
<input type="password" name= "password">
<input type="submit" name= "login">
</form>
-------------
test.php page :

$admins = array("amr", 'osama' , 'mohamed');


$userName = $_POST["username"] ;
$passowrd = $_POST["password"];

if(in_array($userName , $admins)){
echo "welecome " . $userName . " to control panel";
}else {
echo "sorry this username isnot available";
}
-------------
using server method to get the method :

echo "ypu send the data with " . $_SERVER['REQUEST_METHOD'] . ' request ' ;
result : "ypu send the data with POST request sorry this username isnot available "
------------
use server method to check :

if($_SERVER['REQUEST_METHOD']== 'POST') {

$admins = array("amr", 'osama' , 'mohamed');


$userName = $_POST["username"] ;
$passowrd = $_POST["password"];

if(in_array($userName , $admins)){
echo "welecome " . $userName . " to control panel";
}else {
echo "sorry this username isnot available";
}
}else {
echo "you cant brwose this page directlys";
}
"laxem el user yegy 3n tarek el form mynf3sh nkon fel saf7a w n3ml q n5osh 3la el
data"
=====================================

$_REQUEST[] // also used to collect data


if($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_REQUEST['username'];
}
==========================================

cookies[]

note : cookies must writen at the first :

setcookie('amr', "test" , time()+ 3000 , '/');


if(count($_COOKIE ) > 0) {
echo "the cookies is enabled" ;
}else {
echo "the cookies are not enaled" ;
}

result : "the cookies is enabled"


------------------------------

setcookie(name, value , expire , path , domain , secure ,httponly)

Name : name of the cookie .


value : content of the cookie ,
expire : expireation date .
path: path of the page which i will put the cookie
path :["/'] : means all pages iside the cookie .
domain : the domain of the page
secure : true or false
ex ;
setcookie('twitrer', "osama" , time()+ (68400*10) , '/', 'localhost' ,true , true);

note : 68400 is time day .

echo "<pre>";
print_r($_COOKIE);
echo "</pre>";

==========================================
simple example to make cookies color :

<?php

$mainColor = '#FFF'; //main color


if( $_SERVER['REQUEST_METHOD'] == "POST" ) {
$mainColor = $_POST['color']; // get the colo from the form input
setcookie("background", $mainColor , time() + 3600, '/' );
}
if(isset($_COOKIE['background'])) { // if cookie is exist
$body = $_COOKIE['background']; // make variable body to make background
}else{
$body = $mainColor ; // reset the background
}

?>
<!DOCTYPE html>
<html>
<head>
<title>content</title>
<style>
</style>
</head>
<body style = "background-color :<?php echo $body; ?>" >
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type="color" name ="color">
<input type="submit" name ="choose" value="choose">

</form>
</body>
</html>
<head></head>

==================================
To delete a cookie, use the setcookie() function with an expiration date in the
past:
setcookie("user", "", time() - 3600);
=====================================
session :

room1 :

session_start() ; // start session or resume


$_SESSION['username']= 'osama' ;
$_SESSION['favfood'] = 'pizza';
echo '<a href="test.php">Room number 2 </a>';

result :Room number 2 //link


-------------------
room2 :

session_start() ;
echo "hellow ". $_SESSION['username'] . "how aare you" . "<br>";
echo "your favorite food is : " . $_SESSION['favfood'] ;
echo '<a href="page3.php">Room number 3 </a>';

result : hellow osamahow aare you


your favorite food is : pizzaRoom number 3
--------------------------
room3 :

session_start() ;
echo "hellow ". $_SESSION['username'] . " u are in page 3 " . "<br>";
echo "your favorite food is : " . $_SESSION['favfood'] ;

result : hellow osama u are in page 3


your favorite food is : pizza

-----------------------

modify session :

room4 :

session_start() ;
$_SESSION['favfood']= 'chicken'; //session moodiefied in page four
echo "hellow ". $_SESSION['username'] . " u are in page 4 " . "<br>";
echo "your favorite food is : " . $_SESSION['favfood'] ;
-------------------------

session destroy : // logout

session_start() ; //resume the session


session_unset(); // unset the session
session_destroy();

print_r($_SESSION);
===========================

simple counter by session :

page1 :

<?php

session_start() ; // start session or resume


$_SESSION['username']= 'osama' ;
include "test.php";
echo '<a href="page3.php"> page3</a>'
?>

-----------
<?php

session_start() ; // start session or resume


echo "hello ". $_SESSION['username'] . ' how are yout' ;
include "test.php";
echo '<a href="index.php"> index</a>'
?>
========================================================
simple login :

page1 :

<form action="check.php" method= "POST">


<input type="text" name='username'> // the main form
<input type="submit" value='login'>
</form>
-----------------------
page2 :

<?php

session_start() ;
$admins = array("amr" , "kareem" , "mohamed" , "yousef" , "adham");
if($_SERVER['REQUEST_METHOD']== "POST") {
$user = $_POST['username'];

if(in_array($user ,$admins )) {
//if is admin
$_SESSION['user'] = $user ; // if is in array sagelo fel session
echo "welcome ". $_SESSION['user']. ' you will be directed to control
panel area';
header("REFRESH:2, URL = control.php"); // redirection
}else {
// if not admin
echo "adimin not fount";

}
}else{
echo "you cant acsses this page directly";
}
?>

----------------------------
page3 :

<?php

session_start();
if(isset($_SESSION['user'])) {
echo "welecome" . $_SESSION['user']. "you are adimn";
}else {
echo "you are not primted to enter this page";
}
?>
===========================================

sleep(seconds) ; // as delay function in jquery


usleelp(microseconds); // as sleep but use microsecond

ex : // it will delay "sorry" 2 seconds :

$name = 'amr';
echo $name ;
sleep(2);
echo "sorry!" ;
-------
usleelp(5000000) ;
--------------
simple function on sleep() :

<?php

function checkFiles() {
if(file_exists('amr.txt')){
echo "file is found" ;
}else {
sleep(1);
checkFiles(); //repat the function untill it found the file
}
}
echo checkFiles();
?>
-------------
time_sleep_until(time()+ 5) :
=============================
exit() or die() :
ex :
<?php

$name = 'amr' ;
echo $name ;
exit(); // bw2af el ode l8aeyt el 7ta de

echo 'heloo' .$name ;


?>

simple function on exit() :

@fopen('osma.text' , 'r')
or exit("file is not exist") ; //w2af el code l8a' hena mohmea!
echo "ho0";
echo "ho0";
echo "ho0";
resul : "file is not exist"
==================================
uniqid(prefix , more_entropy) : //uniq identidir
<?php
$random = uniqid() ;
echo $random ;
?>

result : "5de95352a836c" or "5de953870c627"


--------------
using prefix : //prevent dublication

$random = uniqid("script1_") ;
script1_5de954822feae
-------------------
using more_entropy : // increase randomize
$random = uniqid("script1_" ,TRUE) ;
result : "script1_5de956756825e6.52416164" ; // 23 charchter
============================================
filters :
/*
user input ,
bad cookies
web service
server variables
database query result
*/

<?php
foreach(filter_list() as $filter) { //show filter_list
echo $filter ."<br>";
}
?>
int
boolean
float
validate_regexp
validate_domain
validate_url
validate_email
validate_ip
validate_mac
string
stripped
encoded
special_chars
full_special_chars
unsafe_raw
email
url
number_int
number_float
magic_quotes
callback
--------------------
filter_var() :
ex :

<?php
$string = $_POST['test'];
echo filter_var($string , FILTER_SANITIZE_STRING ) // snatiize : ta3keem
?>
----------------------------
filter_var(variable ,filter type , options);

<?php

$input = $_POST['test'];
$filter = filter_var($input , FILTER_VALIDATE_INT ); / validate the integer
input
if($filter == TRUE) {
echo "you enterd integer";
}else {
echo 'you dont';
}
?>

"you enterd integer" => if number in the input


"you dont" => if string or any type enterd
======================
$filter = filter_var($input , FILTER_VALIDATE_EMAIL ); / validate the EMAIL
input
$filter = filter_var($input , FILTER_VALIDATE_IP ); / validate the EMAIL
input
// there are many types on website
===============================================

using filter(options) to max max and min number in the input : // options
must be array
<?php

$input = $_POST['test'];
$opt = [
'options' => array(
"min_range" => 1 ,
"max_range" =>999
)
// 'flags' =>
];
$filter = filter_var($input , FILTER_VALIDATE_INT , $opt);
if($filter == TRUE) {
echo "GOOD ! the ". $input ." is between 1 and 999";
}else {
echo 'sorry the ' . $input . 'is not between';
}
?>
--------------
FILTER_VALIDATE_IP example :

<?php

$input = $_POST['test'];
$opt = ['options' => array(),'flags' => FILTER_FLAG_IPV4 ];
$filter = filter_var($input , FILTER_VALIDATE_IP , $opt);
if($filter == TRUE) {
echo "GOOD ! the ". $input ." is version 4";
}else {
echo 'sorry the ' . $input . 'is version 6';
}
?>
result :GOOD ! the 192.168.1.1 is version 4

===============================
validate VS snatiize : // important for security :

<?php

$input = $_POST['test'];

$goodInput = filter_var($input ,FILTER_SANITIZE_EMAIL);

echo "input after santiz " . $goodInput . "<br>";

$filter = filter_var($input , FILTER_VALIDATE_EMAIL);


if($filter == TRUE) {
echo "GOOD !";
}else {
echo 'BAD!';
}
?>
result :
input after santiz [email protected]
GOOD !
=========================

date(format , timestamp) ;
//today :2019-12-07 07:33:18 :

date_default_timezone_set('Asia/Riyadh'); //choose the region


echo date('Y-m-d h:i:s');
result ://today :2019-12-07 07:33:18 :
----------------------
date_default_timezone_set('Asia/Riyadh');
$nextMonth= time()+(30*24*60*60); // make timestamp next month
function(30*24*60*60) 30day * 24hour *60 min * 60 sec
echo date('Y-m-d h:i:s',$nextMonth); // print next month timestamp
result: 2020-01-06 07:35:19 // nextMonth
-----------------
date_default_timezone_set('Asia/Riyadh');
$nextWeek= time()+(7*24*60*60); // next week function
echo date('Y-m-d h:i:s',$nextWeek);

result : 2019-12-14 07:32:28 // next week


----------------------------
date parameters :
echo 'copyrights are reserved to amr &copy; 2010-'. date('Y');
result :"copyrights are reserved to amr © 2010-2019" // waay to use date
------
2- echo date('Y-m-d \of h:m:s'); //esacape backslash
====================
echo date('jS'); // suffex j is print day without zeros , S print suffex (th) :
7th
---------
ex :
today : =7
$afterTwoDays = time() + (2*24*60*60) ;
echo 'after two dayes with sufffex is : ' . date("jS" , $afterTwoDays) ;
result : "after two dayes with sufffex is : 9th"
=======================
advanced example :
echo date("l jS \of F Y d:h:s a" ) ;
result :"Saturday 7th of December 2019 07:06:49 pm"

--------------
advanced example 2 :

$month = 30*24*60*60;
$afterSixMonth = time() +(6*$month);
echo date("l jS \of F Y d:h:s a" ,$afterSixMonth) ;

result "Thursday 4th of June 2020 04:07:27 pm" // after 6 month


===================================================

strtotime(date ,timestamp[now]) //string to time : //easy way instead of old


wa calc // sahla gdn!
1 - $time = strtotime("now"); // time of now-
echo date("Y-m-d :h:i:s" ,$time) . "<br>";
result :"2019-12-07 :06:20:39"
-------------
2- $time = strtotime("now");
echo date("Y-m-d :h:i:s" ,$time - 3600) . "<br>"; // now - 1hour
result : "2019-12-07 :05:25:17'
-------------
3-$time = strtotime("+1 day");
echo date("Y-m-d :h:i:s" ,$time ) . "<br>";
result :"2019-12-08 :06:28:11"
------------
4- $time = strtotime("+2 week");
------------
5- $time = strtotime("+2 year");
result : "2021-12-07 :06:30:16"
-----------
6- $time = strtotime("+20 month");
-----------
7- $time = strtotime("+1 week 2 day"); // one week + 2days
----------
8- $time = strtotime("+1 week 2 day 6 hours"); // one week + 2days+ 6 hours
---------------
7- $time = strtotime("next monday"); // el etneen el gay
---------------
8- $time = strtotime("last friday"); // el gom3a el fatet
======================================

===================================================================================
=============================================================
===================================================================================
===========================================================

MYSQL : database

methods :

1- command line
2-PHP myadmin
3- php software

start connection PDO :

<?php

$dsn = "mysql:host=localhost;dbname=students"; //data sourse name


$user ='root' ; //user to connext
$password = ''; //password
$options= array(
PDO:: MYSQL_ATTR_INIT_COMMAND =>"SET NAMES utf8"
);

try {
$db = new PDO($dsn , $user, $password ,$options ); //start a new
connection with PDO class
$db ->setAttribute(PDO::ATTR_ERRMODE ,PDO::ERRMODE_EXCEPTION); //PDO
OPTIONS IN MANUAL PHP
$query= "INSERT INTO items (name) VALUES ('koko')"; //query
$db->exec($query) ; //excute query
echo "the connection established";
}catch(PDOException $e) {
echo "the connection failed" .$e->getMessage() ;
}

?>
result : if no error : "the connection established"
if an error occuerd : $password = '123'; //password " then
the connection failedSQLSTATE[HY000] [1045] Access denied for user
'root'@'localhost' (using password: YES)
============================================================
data types :

tiny : integer => Max charchters [ 4 ]


small : integer => Max charchters [ 6 ]
medium : integer => Max charchters [ 9 ]
big : integer => Max charchters [20 ]
int : normal integer => Max charchters [ 11 ] 2.147.483.647 max value in mysql
int type
------------------
date => YYYY-MM-DD
datetime => YYYY-MM-DD HH:MI:SS
timestamp => YYYY-MM-DD HH:MI:SS
time => HH:MI:SS
year =>YYY
=============================
String :

Char => charchter


- store fixed value
- max charchter 255
- faster than VarChar
- use static memory

VarChar => variable charchter


- store fixed value
- max charchter => 65,535
- use dynamic memory
ex :
for($i= 1 ; $i<=500 ;$i++){
$stmt = $db->prepare("INSERT INTO `students` .`items`(`myString`) VALUES ('".
$i."')");
$stmt->execute() ;
}
======================
text : store string
- deal with and compared depend in charset
-store long strings like comments

BLOB : binarry large object //images . vedios


- deal and compaerd to bytes
- has no charset

ENUM : /USE ONE CHOOS ONLY in sselect box


SET : USE MULTIPLE CHOICE in sselect box
=======================
deal with database :
mysql -u root // enter mysql
CREATE DATABASE ELZERO ; // cerate database
show databases; // show all databases
use elzero; // use elzero database
DROP DATABASE // delete database
DROP DATABASE IF EXISTS ELZERO ; // delete database if exitis
CREATE DATABASE IF NOT EXISTS Shop; // cerated database if it's not
exits
SHOW DATABASES LIKE 'shop' ;
+-----------------+
| Database (shop) |
+-----------------+
| shop |
+-----------------+
========================================

tables :

// create table
create table students(
id int(11) ,
name varchar(255) ,
email varchar(2550)
);
-------------------
MariaDB [students]> CREATE TABLE AMR (
-> name varchar(255),
-> id int(11) ,
-> email varchar(255) /// create table
in command line
-> )
-> ;
Query OK, 0 rows affected (0.249 sec)
--------------------------------------------------

MariaDB [students]> DROP TABLE IF EXISTS AMR; // DROP


[delete]table if expists :
======================================

MariaDB [students]> describe amr or ,


show column from amr or /// all three commands have same results
wich is table content
show fields from amr ;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name | varchar(255) | YES | | NULL | |
| id | int(11) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | | // describe table
amr
+-------+--------------+------+-----+---------+-------+

========================================================

MariaDB [students]> show CREATE TABLE amr;

amr | CREATE TABLE `amr` (


`name` varchar(255) DEFAULT NULL, // show the code of
creating table to edit in the future
`id` int(11) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |

=====================================

MariaDB [students]> RENAME TABLE students TO kareem , items TO newItems;


//rename table or more than one table
==================================
change storage engine of table :
MariaDB [students]> ALTER TABLE kareem ENGINE =MYISAM; //
change storage engine of the table
==================================

Alter : add
edit : datatype of column ,
edit the column name ,
edit the arrangment of the column,
add new column

-------
ALTER TABLE kareem ADD password varchar(255); // it will add a a new record to
table but at the end
ALTER TABLE kareem ADD address varchar(255) AFTER name;
+----------+--------------+------+-----+---------+-------+
| regligon | varchar(255) | YES | | NULL | |
| id | int(11) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| address | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
| password | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
===========
alter : drop
ALTER TABLE kareem DROP password; /// delete passowrd from coloumn karrem
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| regligon | varchar(255) | YES | | NULL | |
| id | int(11) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| address | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+

========================
change postion of column :
MariaDB [students]> describe kareem;
+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| regligon | varchar(255) | YES | | NULL | |
| id | int(11) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| address | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+

MariaDB [students]> ALTER TABLE kareem CHANGE id id varchar(255) AFTER


name; //change id postion after name

MariaDB [students]> describe kareem;


+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| regligon | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| id | varchar(255) | YES | | NULL | |
| address | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+

====================================================
change the data type of the column :
MariaDB [students]> ALTER TABLE kareem CHANGE id id int(11);

MariaDB [students]> describe kareem;


+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| regligon | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| id | int(11) | YES | | NULL | |
| address | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
============================
modify :
MariaDB [students]> ALTER TABLE kareem MODIFY id int(21); // as CHANGE but
write id one TIME
id | int(21) .
=======================

ALTER TABLE newitems RENAME osama; //use Alter to change name of the table
newitems to osama ;
======================================

use alter , modify at the same line :


ALTER TABLE kareem MODIFY email char(50) , CHANGE id userid int(21);
--------------------------------------------------
| email | char(50) | YES | | NULL |
| userid | int(21) | YES | | NULL |
--------------------------------------------------
======================
change el tarmeez by alter :
ALTER TABLE kareem CONVERT TO CHARACTER SET utf8;
==================================

constraints :
NULL , NOT NULL , UNIQUE , primary key , foregin key

ALTER TABLE kareem MODIFY osama varchar(255) NOT NULL; // add NOT NULL
constraint
ALTER TABLE kareem ADD UNIQUE(osama); // add UNIQUE constraint
ALTER TABLE kareem DROP INDEX userid ; // remove UNIQUE from the table
constraint
ALTER TABLE kareem MODIFY userid int(21) NOT NULL UNIQUE ; //add not null and
UNIQUE at the same line
--------------------------------------------
primary key :

cerate new primary key with new table :

CREATE TABLE teachers (


tid int NOT NULL PRIMARY KEY , // at the same line
tname VARCHAR(255)
);

second method :
CREATE TABLE teachers (
tid int NOT NULL ,
tname VARCHAR(255) , // alone at the end
PRIMARY KEY(tid)
);
----------------
create[ add ] primary key at the existing table :

ALTER TABLE kareem ADD PRIMARY KEY(userid); // add primary key to adress in
table kareem
+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| name | varchar(255) | YES | | NULL | |
| regligon | varchar(255) | YES | | NULL | |
| email | char(50) | YES | | NULL | |
| userid | int(21) | NO | PRI | NULL | | //primary key
| address | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
-----------------------
drop primary key :

ALTER TABLE kareem DROP PRIMARY KEY;

form phpmyadmin //structue ->primary

=================================================
foregin key :

// CREATE table clients :

CREATE TABLE clients( //parent[REFERENCES] table


id int NOT null ,
userName varchar(255) unique ,
email varchar(255) unique ,
PRIMARY KEY (id) // id which know other table
);

-----------------
// create table orders //child table

CREATE TABLE orders(


order_id int NOT null ,
price varchar(255) ,
client_id int NOT null ,
PRIMARY KEY (Order_id) ,
FOREIGN KEY(client_id) REFERENCES clients(id)
);
--------------------
ALTER TABLE orders
ADD CONSTRAINT ordering
FOREIGN KEY(client_id)REFERENCES clients(id)
ON UPDATE CASCADE //CASCADE : any change in parent elemnt shuch
as delete or UPDATE change it in the child
on DELETE CASCADE ;
--------------
ON UPDATE SET NULL //SET NULL : any change in parent elemnt
shuch as delete or UPDATE make the child null
on DELETE SET NULL ; such as example tasks and employee ,
restrict : // prevent delete or UPDATE
===================================================================================
=====
realtions :

CREATE TABLE cards(


card_id int NOT null ,
card_num varchar(255),
client_id int NOT null ,
PRIMARY KEY(card_id),
FOREIGN KEY (client_id) REFERENCES clients(id)
);

one to one : UNIQUE


=====================================
many to many :
// i have table clients , table shops

// table that join clients and shops


CREATE TABLE shopmembership (
client int NOT null ,
shop int NOT null ,

PRIMARY KEY(client ,shop) ,

CONSTRAINT cons_client
FOREIGN KEY (client) REFERENCES clients(id)
on DELETE CASCADE on UPDATE CASCADE ,

cONSTRAINT cons_shop
FOREIGN KEY (shop) REFERENCES shops(id)
on DELETE CASCADE on UPDATE CASCADE

==================================
SELECT * FROM clients JOIN shopmembership ON clients.id = shopmembership.client
WHERE shopmembership.shop = 1;
// -get the members which has shop id 1 .
-----------------------------
SELECT * FROM shops JOIN shopmembership ON shops.shop_id = shopmembership.shop
WHERE shopmembership.client = 20166233;

// search by id get the shops of the clients


=========================================

sting functions :
--------------------
1- LEFT (sting , length);

orginal string :
-----------------
myText |
-----------------
egypt |
saduia araiba |
canada |
--------++-------

SELECT LEFT (myText , 2) FROM try ; // cut the first 2 charchters column
myText
-----------------
myText |
-----------------
eg |
sa |
ca |
--------++-------
==========================================
3 - RIGHT(string , length) ;
SELECT RIGHT(myText , 2) FROM try;

-----------------
myText |
-----------------
pt |
ba | //cuts 2 charchters from right
da |
--------++-------
======================================

2- MID (string , start postion, length OF THE charchterS) ;


SELECT MID(myText ,2 , 3 ) FROM try;

-----------------
myText |
-----------------
gyp |
adu |
ana |
--------++-------
==============================================

LENGTH(string) : OR
CHAR_LENGTH () // mesure the acutal length in charchter as (euro sign)

SELECT myText , LENGTH(myText) as COUNT FROM try // name th column


length :count
------------------------
myText |COUNT |
-----------------------|
egypt | 7 | //length f=of the records
saduia araiba | 13 |
canada | 6 |
--------++-------++-----
----------------------
order sting :
SELECT myText,CHAR_LENGTH(myText) as ordering FROM `try` ORDER BY
CHAR_LENGTH(myText) DESC or AS ;
------------------------
myText | ordering |
-----------------------|
canada | 6 |
egypt | 7 |
saduia araiba | 6 | //larrange the length assendingally
--------++-------++-----

==================================
UCASE(string) // uper case :
SELECT UCASE(myText) as COUNT FROM try ;
LCASE(string) //lower case
=====================================
REPEAT(string , number of repeats);
SELECT myText, REPEAT(myText ,3 ) AS repeted FROM try ;
----------------------------------------------------------------
myText | repeted
------------------|---------------------------------------------
egypt | egypt egypt egypt |
saduia araiba | saduia araiba saduia araiba saduia araiba |
canada | canada canada canada | //repat
the entire string
--------++-------++--------------------------------------------

-------------------------------------------
REPLACE(string , from ,to) ;
SELECT myText, REPLACE(myText ,'a' , '@' ) AS replaced FROM try ;
-------------------------------------+
myText | repeted |
------------------|------------------|
egypt | egypt |
saduia araiba | s@dui@ @r@ib@ |
canada | c@n@d@ | //change the charchter "a" to "@"
inall column
--------++-------++------------------+

use replace in real life :


UPDATE `try` SET myText = REPLACE(myText, 'http' ,'https); //
change any http to https
http://www.facebook.com/ //to https://www.facebook.com/
--------------------------------------------
REVERSE(string ) ;
SELECT myText, REVERSE(myText) as reversed from `try` ; //
revers the text
egypt => tpyge ,
saduia araiba => abiara aiudas ,
canada => adanac
======================================

CONCAT(string , string ,string..) ;


SELECT myText , CONCAT('hello ' ,myText , ' made by me' ) as newtext FROM `try` ;
//concatetion text beside my text

result :saduia araib || saduia araiba made by me


--------------------
CONCAT_WS(seprator , string , string ..) ; //
concatetion with seprator (comma or @ or $ ,etc .. )
SELECT myText , CONCAT_WS(",",myText , 'added' ) as newtext FROM `try` ;

result :
"egypt , added "
"saduia araiba , added"
"canda , added "
=======================================
string :
INSERT(string , postion , length , new string)
SELECT myText , INSERT(myText,3,2 , 'amr')AS INSERTED FROM `try`;
-------------------------------------+
myText | INSERTED |
------------------|------------------ |
egypt | egamrt |
saduia araiba | saamria araiba |
canada | caamrda | //replace from postion 3 two
charchters by new string
--------++-------++------------------+

another ex :
UPDATE `try` SET myText = INSERT(myText, 3,2,'serial');
=======================================================
TRIM(methods[leading | trailing | both] [remove string]FROM String) :
- methods optional if NOT writtten both will be used
- removeed string if NOT used space will be removed

ex 1 :
SELECT `name` , trim(name) FROM `try` or SELECT `name` , trim(BOTH,name) FROM
`try
old : osama
new :osama
---------
with leading: // cut from left only and leave right space
SELECT `name` , trim(LEADING FROM name) FROM `try`
old :osama // here space
new : osama
------------
with option trailing: // cut from right
SELECT `name` , trim(TRAILING FROM name) FROM `try`

old :osama // here space


new :osama
---------
use string to remove:
SELECT `name` , trim(LEADING '@' FROM name) FROM `try` // leading
---------------------------+
name | trimmed |
--------------------------- //cut from the left '@' charchter
@@amr@@ | amr@@ |
---------------------------
=====================================
SELECT `name` , trim(TRAILING '@'FROM name) FROM `try`
---------------------------+
name | trimmed |
--------------------------- //cut from the right '@' charchter
@@amr@@ | @@amr |
---------------------------
========================================
---------------------------+
name | trimmed |
--------------------------- //cut both '@' charchter
@@amr@@ | amr |
==================================================
LTRIM(string) : //remove spaces only from left
SELECT `name` , ltrim(name) FROM `try`
=============
RTRIM(string) : //remove spaces only from right
SELECT `name` , Rtrim(name) FROM `try`
=====================================
LPAD(string ,length ,padded string );

SELECT `names` AS oldNames , LPAD(`names` , 5 , "@") AS paddedString FROM `try`

-------------------------------------+
myText | paddedString |
------------------|------------------ |
os | @@@os |
mah | @@mah |
osama elzero | osama | // i want 5 charchters only and it add the
sting[@] to the string if its exseesd it will not add anything
--------++-------++------------------+

RPAD(string ,length ,padded string ); // the same but right[mah@@]


===================================================================================
==
Math functions :

CEIL(number) ;
SELECT numbers as old , CEIL(numbers) as new FROM `try` ;
FLOOR(number);
ROUND(number, decimal(2 or 3 ... ));
=================================
TRUNCATE(number , decimal) ;
SELECT numbers as old , round(numbers) as rounded ,
TRUNCATE(numbers , 2) as truncated FROM `try`

---------------+----------------------+--------------+
old | rounded | truncated |
---------------+-------------------------------------|
4.5 | 4 | 4.50 |
4.5995879 | 5 | 4.59 |
1.6587699 | 2 | 1.65 | //diffrence between
truncate and round is truncate takes the two number but dosent aproxmiate
--------++-------++------------------+---------------+
---------------------
POW(numebr, powerd) ; //power //so easy
POW(2,2) : result : 4
-----------------------
MOD(number,mod); MOD(21,5) : result: 1
=======================================================================

DATE & Time functions :

CURTIME() OR CURRENT_TIME() or CURRENT_TIME; // all are the same


//local time
HH:MM:SS
==============================
CURDATE() OR CURRENT_DATE() OR CUURENT_DATE; //get local date
YYYY-MM-DD
==============================
NOW(); or CURRENT_TIME_STAMP() // get local date and time
2019-12-14 12:56:41
==============================

DAYNAME(date);
SELECT CURRENT_DATE() , DAYNAME(CURRENT_DATE()) AS todayName
------------+-----------+--|
CURRENT_DATE() | todayName|
------------+-----------+ |
2019-12-14 | Saturday |
------------+-----------+--+

set date :
SELECT CURRENT_DATE() , DAYNAME('2016-07-30') AS nextWeek
==============================

DAYOFMONTH(date);
SELECT CURRENT_DATE() , DAYOFMONTH(CURRENT_DATE()) AS monthdate

------------+-----------+--|
CURRENT_DATE() | monthdate|
------------+-----------+ |
2019-12-14 | 14 |
------------+-----------+--+

==============================
DAYOFWEEK(date);
==============================

DAYOFYEAR(date); //the number of days


in the year
SELECT CURRENT_DATE() , DAYOFYEAR(CURRENT_DATE()) AS yearDate

------------+-----------+--|
CURRENT_DATE() | yearDate |
------------+-----------+ |
2019-12-14 | 348 |
------------+-----------+--+
========================
MONTH(date);
SELECT MONTH(CURRENT_DATE());
result : 12
==============================
MONTHNAME(date);
SELECT MONTHNAME(CURRENT_DATE());
result : December
==============================
HOUR(date);
SELECT HOUR(CURRENT_DATE());
result : 8
==============================
MINUTE(date);
SELECT MINUTE(CURRENT_DATE());
result : 17
==============================
DATEDIFF(date1 , date2) //date diffrence // very important
ex:
SELECT id, personDate , name ,
CONCAT( 'regesterd',DATEDIFF(CURRENT_DATE() ,personDate) , 'days ago') as
numberOfDays FROM `try` //diffrence between CURRENT date and the puted date

---------------+----------------------+--------------+----------+------+
id | personDate | name | numberOfDays |
---------------+-----------------------------------------------+----++++
1 | 2019-12-18 02:12:05 | KOKO | 4 days ago |
2 | 2019-12-11 08:02:01 | MOHSEN | 3 days ago |
2 | 2019-12-10 02:02:0 | aamr | 3 days ago |
--------++-------++------------------+---------------+----------+------+
==========================================================================

LAST_DAY(date); // type of month last day such


as [31 , 30 , 29 ] months
DATE_ADD(date , INTERVAL + TIME UNIT ); // add period to existing date
DAY_SUB(date , INTERVAL + TIME UNIT ); // add period to existing date

example :

SELECT id , personDate , name,


DATE_ADD(personDate, INTERVAL 10 DAY) AS added_10_days ,
DATE_SUB(personDate, INTERVAL 5 month) AS subtracted_5_month ,
LAST_DAY(personDate) AS lastdayInTheMonth
FROM `try`;

---------------+----------------------+--------------+----------+-------
+------------------------------------- |------------------+
id | personDate | name | added 10 days |
subracted_5_month |lastdayInTheMonth |
---------------+-----------------------------------------------+--------
+------------------------------------- |-------------------
1 | 2019-12-10 02:12:05 | KOKO | 2019-12-20 02:02:01 |
2019-07-10 02:02:01 | 2019-12-31 |
2 | 2019-12-11 08:02:01 | MOHSEN | 2019-12-21 02:02:01 |
2019-07-10 02:02:01 | 2019-12-31 |
2 | 2019-12-10 02:02:0 | aamr | 3 days ago |
2019-07-10 02:02:01 | 2019-12-31 |
--------++-------++------------------+---------------+----------
+----------------------------------------------+------------------|
===================================================================================
=========================================

comparision functions :

BETWEEN AND : // [minumum <=expr AND <=maximum]


ex: SELECT * FROM `try` WHERE `id` BETWEEN 2 AND 6
result :
------+
2 |
3 | // [minumum <=2 AND <=6]
5 |
------+
ex:2 : SELECT * FROM `try` WHERE `id` BETWEEN '2016-5-18' AND '2016-08-25'

ex:3
SELECT * FROM `try` WHERE
`personDate` BETWEEN DATE_SUB(CURRENT_DATE() ,INTERVAL 2 MONTH) AND
CURRENT_DATE() ; last tow months - current date
----------------------------
NOT BETWEEN AND :
SELECT * FROM `try` WHERE `id` NOT BETWEEN 2 AND 6
1
7
==========================================================
IN
SELECT * FROM `try` WHERE `id` IN (2,5 , 6, "osama") //get the idS of these
numbers [if its no exists dont worry ]
--------------------------------
NOT IT /// all exept numbers in the brackets
SELECT * FROM `try` WHERE `id` NOT IN (2,5 , 6, "osama")
==========================================================
LIKE
% : (empty or collecttion of charchters) : means unknowen [.....]
SELECT * FROM `try` WHERE `name` LIKE '%amr'
sELECT * FROM `try` WHERE `name` LIKE '%sen%';
sELECT * FROM `try` WHERE `name` LIKE '%a%' :osama ,aamr
sELECT * FROM `try` WHERE `name` LIKE 'm%n'
NOT LIKE
-------

_(one charchter).
ex : SELECT * FROM `try` WHERE `name` LIKE '_sama' result : osama , asama
ex: SELECT * FROM `try` WHERE `name` LIKE 'sam_h': result : sameh , samah

-------------------
NOT LIKE : .ex : SELECT * FROM `try` WHERE `name` NOT LIKE '%sama' // all
expec this

===================================================================================
=========
comparision opertaors :

= [equal ] : SELECT * FROM `try` WHERE id = 1


>[more than ]SELECT * FROM `try` WHERE id > 1
<[less than] : SELECT * FROM `try` WHERE id < 1
<=[less than or equal] : SELECT * FROM `try` WHERE id >=1
![not equal] :SELECT * FROM `try` WHERE id != 1
======================

logical operators :
AND : SELECT * FROM `try` WHERE `name` LIKE '%sama' AND id > 100
NOT: SELECT * FROM `try` WHERE `name` NOT LIKE '%sama'
OR : SELECT * FROM `try` WHERE `name` LIKE '%sama' OR id > 100
XOR [A condition and not B condition]: SELECT * FROM `try` WHERE `name` LIKE
'%sama' XOR id > 100
[B condition and not A condition]:
===========================================

control flow functions() ;

IF(condition, true , false)


ex :
SELECT name , if(id >2 , 'good luck' , 'bad luck') as result FROM try;

-------------------++++
id | resluts |
1 | bad luck |
1 | bad luck |
2 | bad luck |
3 | good luck|
5 | good luck|
0 | bad luck |
0 | bad luck |
10 | good luck|
------------------- --|
================================
Case :
SELECT name ,id ,
CASE
WHEN `id` = 1 THEN 'good luck '
WHEN `id` = 2 THEN 'ex luck '
WHEN `id` = 5 THEN 'amazing luck '
WHEN `id` = 0 THEN 'bad luck '
END as result
FROM `try`;

result :

-------------------------+
id | resluts |
1 | bad luck |
1 | bad luck |
2 | ex luck |
3 | good luck |
5 | amazing luck|
0 | bad luck |
0 | bad luck |
------------------- -----
=========================================

You might also like