Decoding from Json String
````````````````````````````````
inorder to decode the entire Json string we can use json_decode() to convert JSON_STR to native PHP DataType
Syntax:
json_decode(<json_str>,<to array>[default=false]);
Return Type : Object | Array | Key
How to decode the entire Json String to Array
Syntax :
$data=json_decode(<json_str>,true);
echo getType($data); //array
#Iterating through Object
foreach($json_array as $json_obj){
echo $json_obj->key_1;
echo $json_obj->key_2;
echo $json_obj->key_3;
echo $json_obj->key_4;
.......
}
Q. What is the difference B/W Json_encode and Json_decode
1. json_encode : Converts PHP Native Objects to Json Object String
2. json_decode : Converts json_string to php native DataTypes which will be object if second argument kept as false and array if second Argument kept true.
Asyncronous Programming in PHPMYADMIN
--------------------------------
Asyncronous means doing multiple task Parallely
Syncronous means doing task one after the other it will wait till the first task is completed.
Why do we required concept of Asyncronous Programming
It is because JS is event Based and PHP is Page Load Based(Response)
if event Occurs Response will wait
Response will occur then event will wait
Deadlock condition will occurs
That is why we need Asyncronous Programming
This can be done using Concept Of Ajax
Ajax:
-----
Ajax: Asyncronous JavaScript and XML Response : Content-Type:application/xml
Ajaj : Asyncronous JavaScript and Json response : Content-Type: application/json
Ajay : Asyncronous JavaScript and Yml Response : Content-Type: application/yml
How to Achieve:
```````````````````
You need to send Asyncronous Request:
Vanilla.js or Pure JavaScript
var http=new XMLHttpRequest();
http.open("url");
http.send("url",true,"GET/POST");
| | |----Method GET/POST
| |--------------->is Asyncronous
url where to send data
Using Jquery
$.ajax({
url:"getdata.php",
dataTYpe:JSON|XML|YML|"text",
type:"GET/POST",
success:function(response){
// js Code
// code is key in Json Object returned by PHPMYADMIN
if(response.code==200){
//js code but data binding
}else{
console.log(response);
}
},
});
28/01/2021
--------
How to run JS and PHP Parallely
``````````````````````````````````
<script type="text/javascript" src="path/to/js.php"></script>
How to use js.php
````````````````````````
<?php
header("Content-Type:text/javascript");
?>
var base_url = "<?php echo AJAX_PATH; ?>";
window.alert("hi");
if you try to include any php file in a root folder
then autoloader Configuration Must be required.
goto admin/folder
copy .htaccess file
Keep and any custom root folder you created. For example(php_js)
m
Register the definition and path for php_js
inside php_js
|------>.htaccess (copied from admin/)
|------>myjs.php
Goto config/Config.php
$modular['php_js']='php_js';
29/01/2021
```````````````
Ambiguity in Ajax Request
`````````````````````
Since each and every request is processed Via server timestamp for each request is calculated tracked by server
Any request with same identity will processed first which is arranged in Memory Stack first.
That is why each request must be sent Uniquely
For-Example:
for email:
http://localhost:8000/myproject/blog-application/web-app/ajax/check_email.php=Valid Request for HTTP/1.1 OK
for Mobile:
http://localhost:8000/myproject/blog-application/web-app/ajax/check_mobile.php=Valid Request for HTTP/1.1 OK
How to hide extension using htaccess
`````````````````````````
RewriteRule ^<(Regex_match)>$ <Resource_name>
Note: Query String is allowed in Case of Rewrite Rules
Magic Constants In PHP
``````````````````````````````````
All the variable must be defined with prefix $ and function with suffix () parenthesis.
but Constants are defined Generally in UPPERCASE and with not prefix and suffix
How to Make Constants In PHP
``````````````````````
define('CONSTANT_NAME','value');
How to use:
echo CONSTANT_NAME;
All Constants are Global can be Accessed anywhere
Scope of Context: Global
<?php
#WAP to define your own User defined Constants.
define('GRAVITY',9.8);
echo GRAVITY;
function test(){
echo GRAVITY; //Global Scope
}
#calling of test
test();
define('GRAVITY',10); //cannot be Resigned
Magic Constants are predefined Constant in PHP and Capable to provinding
runtime values
These Magic Constants have __ as prefix and __ as suffix
Few of them
1. __FILE__ : give the entire path for a file
Example : file name header.php
echo __FILE__
C:/xampp/htdocs/path/to/folder/layout/header.php
2. __DIR__ : give the entire path for a file parent folder
echo __DIR__
C:/xampp/htdocs/path/to/folder/layout/
3. __NAMESPACE__ : Give the name_space name
4. __CLASS__ : Give the Current Class Name
5. __LINE__ : Give the Line Number where execution is Done
6. __FUNCTION__ : Give the function of being Called
7. __METHOD__ : Give the method name of a class
8. __TRAIT__ : To give the Trait Name(Multiple Inheritance Expection)
__NAMESPACE__, __CLASS__, __METHOD__ will be discussed on chapter OOPS
30/01/2021
````````````
How to make Stripped Tables:
31/01/2021
``````
Introduction to Object Oriented Design Pattern
```````````````````````
What is design Pattern:
This means Programming Paradigm (Approach of Programming) or Methodology
Till Now you would have used piece of code in repeated Manner.
In order to Resolve the DRY Approach (Donot Repeat Yourself)
Hence we introduced concept of Functions.
Type of Approaches
1. monolythic : Code in Repeated Fashion (Repeated Approach)
All Code will be written in single File itself.
No One uses this in industry
2. polylithic:
All Code Destributed in Multiple File Approach
1. Functional Approach
2. Object Oriented Approach
3. Design Pattern
There are Total 23 Design Pattern
Ex.
(1). Singleton Pattern
(2). Observer Pattern
(3). Adapter Pattern
(4). Factory Pattern
(5). Fascade Pattern
etc...
Functional Approach
``````````````````````
We divide the piece of code into blocks of functions
Disadvantages of Functions Approach
1. Security (Because function does not private, Public,protected [Access Modifier])
2. Context : Global or Local Context problem arises with version
3. Undefined Variable Errors (Donot have Garbage Collector)
4. Top to Bottom Approach
Object Oriented Approach
````````````````````````````````````
It is a Programming Methodology or Programming Paradigm
It is software development Mechanism with Additional Advantages
Like
1. Security By Using[Access Modifier] like Public, Protected,Private
2. Context: static or Non static
static Object cannot be made
non static object can be made
1. localhost
2. global
public
private
protected
blank Modifier(default): Note that there is no Keywordd for this.
Ex.
1. public Modifier
functions:
public function function_name();
variables:
public variablename
2. private Modifier
functions:
private function function_name();
variables:
private variablename
3. protected Modifier
functions:
protected function function_name();
variables:
protected variablename
4. default modifier
functions
function function_name();
default variable
var <variable>
Context Rules: same as Public
3. Garbage Collector
if dont Initialise the variable
it will be by default Null
In Procedural
$x;
echo $x; // undefined Variable $x;
In Oops
public $x;
private $x;
var $x;
protected $x;
echo $this->x //Null
Real Time Example
``````````````````````
consider a Model
User_model
class User_model{
private $tablename = $db['prefix'].'users';
}
consider a Model
User_model
class User_model{
private $tablename = 'tb1_users';
}
4. Bottom to Top Approach
if you use procedural Approach
``````````````````````
$x;
echo $x; // Undefined Index in line no 1
Object Oriented
class Test{
public $x; <-------------------|
echo $this->x; |
} |
To Top
//No Output |
As Soon as we make Object |
$obj = new Test(); //Instantiate <---Bottom---|
$obj->x=10;
OOPL: Object Oriented Programming Language
Any Programming Language which follows OOPS Concept or Patterns are said to be OOPS(s)
Example to Object Oriented Pattern
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Test{
public $x; //variable inside class Instance Variable
public $y; // variable inside class Instance Variable
//function inside class = Method
public function add($x,$y){
echo $x; // local variable
echo $y; // local variable
echo $this->x + $this->y; //instance
}
}
Basic Terminology:
~~~~~~~~~~~~~~~~~~~~~
1.Instance Variable: class level elements or variables
1. All the variables defined inside class but outside the method
2. All the variables wrapped inside class
3. All the variables encapsulated(covered) inside a class
2. local variables:
1. Any variable outside the class
2. Any Variable inside the class but inside the method
3. Method: Any function declayred inside the class is nothing but method
1. All functions defines inside class
2. All function wrapped inside class
3. All function Encapsulated Inside class
Class = variables + functions()
or
Class = instance variable + methods()
or
Multiplying By wrapping both side
wrapping(class)=wrapping(instance variable) + wrapping(methods)
wrapping(class)=wrapping(variables) + wrapping(function())
but wrapping = Enscapsulation
Enscapsulation(class) = wrapping(variable)+ wrapping(function())
Enscapsulation(class) = wrapping(Instance variable)+ wrapping(methods())
or
In General
Class is a Encapsulated version of variables and functions
variable defines properties
functions defines behaviour
class = collection of properties + behaviour
= collection of states(attributes) + behaviour(actions())
For Ex.
class Student{
public $name;
public $roll;
public $class;
public function scoreMarks(){
}
public function sayName(){
}
public function willstudy(){
}
}
Q. You have Table student
student
Id | name | class | marks | passed
covert the same database schema object oriented approach.
class Student{
public $id;
public $name;
public $class;
public $marks;
public $passed;
public function student_name(){
return $this->name;
}
public function student_class(){
return $this->class;
}
public function student_marks(){
return $this->marks;
}
public function student_passed(){
return $this->passed;
}
public function student(){
echo $this->id;
echo $this->name;
echo $this->class;
echo $this->marks;
echo $this->passed;
}
}
This is Typucal Example of Student_Model
How to create data
`````````````````````
Consider 3 records
1001|ravi|12th|100|yes --->R1
1002|chaman|9th|80|yes --->R2
1003|rahul|10th|90|yes ---->R3
1004|harsh12th|20|no -----R4
Data = Collection of Records or Rows
Each Row Represents A unique Identity
For Example Ravi
Each Unique Identity is a entity
So each Entry Must be represented in a diagram called a entity Diagram
Each Parameter like class,marks,passed,name is inter-related to ravi
Each Entity is inter-related
And Diagram Representation these inter-related among entity is called ER Diagram
student Table = Student Class
name column = name variable
marks column = marks variable
rollno column = rollno variable
id column = id variable
insert = Add student method
update = deleted student method
select = getstudent method
Row = object
Entity = Entity
Object is real Existing Entity
List of Student
1001|ravi|12th|100|yes --->R1
1002|chaman|9th|80|yes --->R2
1003|rahul|10th|90|yes ---->R3
1004|harsh12th|20|no -----R4
student1=new Student();
student1->add_student("1001","ravi","12th","100","yes")
Dynamic:
$student = array(
array('id'=>'1001','name'=>'ravi','class'=>'12th','marks'=>'100','passed'=>'yes'),
array('id'=>'1002','name'=>'ravi','class'=>'12th','marks'=>'100','passed'=>'yes'),
array('id'=>'1003','name'=>'ravi','class'=>'12th','marks'=>'100','passed'=>'yes'),
array('id'=>'1004','name'=>'ravi','class'=>'12th','marks'=>'100','passed'=>'yes'),
);
$i=1;
foreach($students as $student){
$student_obj.$i = new Student();
$student_obj.$i
}
Class in general:
class is a blueprint of object
class is a collection of multiple objects having same instance.
class is a template of a object
class is collection of data member(variable) and member function(methods)
Language Fundamental for a Class and objects
``````````````````````````````````
Under naming convention few convention are mendatory under language Fundamental.
1. Class name must be Capitalised
class test ----> Invalid
class Test ------> Valid
class TEST -----> invalid
2. File Name Containing or One or Single class be Capitalised.
Student.class.php Class File name Must be Capitalised
Another Approach
Root Project
|
|classes
|-->student.php ---> This is class but invalid File name
|-->Student.php ---> This is valid file name
class Student{
}
Class name be alphanumeric but not Numeric Alpha
Spaces are not allowed in class for space seperated class name _ is recommended
Class Student model{
}
This is invalid because of space.
but space can be ignored using _
Class Student_model{
}
in case of objects Naming convention remains same
but you can use either lower or uppercase or block letter None of My Bussiness
since objects followed by $ so they are like a special variable
hence naming convention of objects remains same as of variables
PDBC and WebApi`s
````````````````````````
Generally if you want to store data like username,email,password we make variable
but if there are 100`s of record we cannot do anything with variable then we required array.
But this data storage Mechanism only remains in stack memory.
or
Even if it is stored in Heap data is not permanent what i mean is.
Till the php Virtual Machine is on and script is Executing the data remains and As soon script is terminates PHP vertual MAchine comes to Halt(Pause or Terminate State) and data at Primary Memory flush Out that means data is destroyed.
Note: PHP vertual Machine means PHP Interpreter.
In Order to make data permanent we must use permanent storage machenism.
1. File System Mechanism: Data written into a file is called File Based Storage
Most Common Feature of any framework is to store the exeption and data in Logs file.
In Apache or Xampp we have error.log
In order to store the in log files we need to use File Handling
WAP to make a logger
Let us make a function write_log($msg);
Advantage:
``````````````````
To Log those Request and Output which are implicitly called or hit.
For example:
OTP Email Services,SMS Services.
Do our System or Apache Use Logging
Yes :
error.log : gemerated by Apache
php.log
#Which Logging Technique is used by Server for Authentication
SESSION Logging : Logging a session data into a file.
2. Database Mechanism:
Data written to a tables in rows and columns
Amp stack provides Concept of PDBC (PHP Database Collection)
php can be connected with Any database
Oracle
sybase
db2
informix
monogodb
mariadb
....
When To Use:
when data is In Lacs and Crores
php is confertable with mysql only
but it can match with any databse
It is Apple to apple comparision
for ex..
Romio Julette
Java Oracle
php mysql(past)
php MariaDB
Connection with php to any Database is called PDBC.
Note:
PHP This! - A Beginners Guide to Learning Objected PHP
3. DataWare Houses
4. BigData
5. Data Structures
Working MariaDb or Mysql databse
`````````````````````````
Here Our database is Mysql but owned MariaDB
There are two types of database
1. Logical Database : Oracle is a Logical Database
2. Physical Database : Mysql or Maria db is Physical Database. (Write the data in form files)
What is the Proof
```````````````````
goto c:/xampp/mysql/data
|
| here you will get all the data of the database
Database Logging : Writing the database related stuff into file system
Database Name: Foldername
tablename : tbl_tablename.ibd or *.ibd
columns_schema : *.frm
How many Tables you can store or how many .ibd files can be made
4 Billions approx
How many *.frm files or columns can be stored in a table 4096 Max
How Many ways you can use mysql database
1. Using Heidi SQL(Remote Access)
2. Using MYSQL GUI TOOL (Mysql Workbench)
3. Using Mysql Terminal(console) or cmd
4. using WebBrower (PHPMYADMIN)
Working with mysql console
```````````````````````````
mysql> Console or Query
mariaDB> Commands or Query
1. Connect to mysql>
goto the Root Loaction
Open cmd
cd c:/xampp/mysql/bin/
Command to connect
Every database has a super user
mysql super user:root
You need to connect Root
syntax:
mysql -u <user-name> -p <password>
How to connect by hidden mode
mysql -u <user-name>
Enter Password: ****
By default Password is Blank
Hit Enter
mysql -u <user-name>
Enter Password: <hit Enter>
Never ever set the Mysql path to ENV VARIABLES
it can be access to by Any Third party service
Write a Kernal Program to Execute the Mysql from temperory Environment
Kernal Programming can be done by using CMD
@echo off
set /p name=Enter the Username:
set path=c:/xampp/mysql/bin/
mysql.exe -u %name% -p
pause
write the code to any file
with extension mysql.cmd file..Type all files
How to show all the database
`````````````````````
MariaDB [(none)] show databases;
|
Current database name
Mysql Comments
--comment line--
Create the Database
MariaDB [(none)] create database <db-name>;
|
Create command is used to create database Object
database Objects
1. sequence
2. trigger
3. cursor
4. view
5. database
6. table
7. user
8. privaleges
9. schemas
10. rights
11. permission
12. temperory Table
....etc
How to use database
`````
MariaDB [(none)]> --this is a comment--
MariaDB [(none)]> use logs_db;
Database changed
MariaDB [logs_db]>
Since Database is collection of tables related Entities
for example
database can contain views (virtual Table),schemas,(Tables)
There is table inside a database what is its name
dual table = it is a dummy table which has only record no schema(structure) this table generated at runtime for calculation part
#Describe <tablename>
You will get the schema.
desc dual; #ERROR because dual not have structure.
dual has one row and one column
performing calculation using dual
MariaDB [logs_db]> select 100+100+100 as total_salary from dual;
----------------
| total_salery |
----------------
| 300 |
---------------
MariaDB [logs_db]>
#show all the tables
Syntax: show tables;
if no table is there... Empty set
Data Structure of tables
Array : datatype(ENUM SET)
variables
DataTypes
hash
Btree+
stack
Queue
Index
set = Rows or Records
tuple = this data structure when you insert multiple records in a table.
Creating the Tables
`````````````````````
Syntax:
CREATE table <table-name>(
-><field_name> <datatype>(size) <constrant1> <constrant2> <const...>,
<field_name> <datatype>(size) <constrant1> <constrant2> <const...>,
<field_name> <datatype>(size) <constrant1> <constrant2> <const...>,
<field_name> <datatype>(size) <constrant1> <constrant2> <const...>,
<field_name> <datatype>(size) <constrant1> <constrant2> <const...>
);
CREATE table tbl_logs(
id int(11) not null primary key auto_increment,
name varchar(255) not null,
action varchar(255) not null
);
How to see table schema
desc <tablename>
describe <tablename>
#Query Created Table
syntax:
show create table <tablename>
#Inserting the Records:
insert in specific columns
insert in specific columns
insert into <tablename>(
Fieldname-1,
Fieldname-2,
Fieldname-3,
.....
) values(
'value1',
'value2',
'value3',
);
into:: into a
All these function are used when you want to get the data
1. mysqli_num_rows()
2. mysqli_fetch_array()
3. mysqli_fetch_assoc()
4. mysqli_fetch_row()
5. mysqli_fetch_field()
All these function will used during write operation
writable operation
update or delete
6. mysqli_affected_rows() ::no of affected rows in case delete and update
-1 0 1 min one Affected => True
-1 0 (n) max n affected => True
true
|----> when Query is failed
$check_count = mysqli_affected_rows($con);
if($check_count>0){
}
insert
7. mysqli_insert_id($con)
gives Id of last inserted record
select max(id) from any_table
Postmartem of result set functions
*******************************
1. mysqli_num_rows()
2. mysqli_fetch_array()
3. mysqli_fetch_assoc()
4. mysqli_fetch_row()
5. mysqli_fetch_field()
This result set is also called resource and denoted by #n
where n=1,2,3,4,5,6,7,8.......
$con :: is reponsible for profiling
SQL Query
Explain <Any-Query>
In order to check the unique whether a record exist or not
we use $count > 0 record exist
Select Query::
$count=mysqli_num_rows($result_set);
/*
write to the database
following all the step to perform Crud Opearation using PHP Database Connection
Step-1:
create the database connection
mysqli_connect($host,$user,$pass,$dbname);
Return $connection_str or $Connection Object
$con = mysqli_connect($host,$user,$pass,$dbname);
$con = mysqli_pconnect($host,$user,$pass,$dbname);
|
persistant Connection
(Permanent Connection)
#dbconnect.php
since connection is made only once
$host = '127.0.0.1'; localhost
$user = 'root';
$pass = '';
$dbname = '';no Error
$dbname = 'dbname'; #database Name is correct then ok if
#wrong Exception will be raised
note:: i here means Improved version
Steps2: Check if connection is made or not
method 1:
try{
$con = mysqli_connect($host,$user,$pass,$dbname);
echo 'connection Created';
}catch(Exception $e){
if(!$con){
die("Connection Error".mysqli_error($con));
}
}
Method2:
if($con){
echo 'connection Created';
}else{
echo "Connection Error".mysqli_error($con);
exit;
}
method 3:
$con = mysqli_connect($host,$user,$pass,$dbname) or die('connection Error');
Step3:
prepare the Query and Fire the Query
Step4: justify the type of Query
if it is writable or readable
if it is writable or readable
if query is readable return type will be Result Set select = Result set
If query is writable
return type no of affected Rows
minimum Affected rows 1
1 => true
if($check==true){
echo 'Insert Ok'; #insert
echo 'Update Ok'; #update
echo 'Deleted Ok'; #delete
}else{
echo 'Insert|Delete|Update Error';
}
#Preparing the Query
$sql = "INSERT OR UPDATE OR SELECT OR DELETE QUERY";
#Fire the Query
1. writable
insert,delete,update,alter,create,drop,truncate....
mysqli_query($con,$sql)
| |--->sql
|------>connection object
Syntax:
$result = mysqli_query($con,$sql);
return type: true|false
2.Readable
select,joins,projection,selection,transaction
mysqli_query($con,$sql)
|--->sql
|----->connection object
return type : Result Set :: Multi-Dimension Array of N
Records
Note::
$sql = "Query 1;";
$sql = "Query 1;";
$sql = "Query 1;";
$sql = "Query 1;";
mysqli_query($con,$sql);
*/
database connection
0 Comments