php+mysql+cookie + modular development

PHP

PHP output
<?php

	echo "Hello";
	echo("Hello");
	print("Hello");
	print "hello";
	
	var_dump("Contact PHP");//Code debugging uses this
Define variables

php is a weak reference language, so it's easy to use.

data type

array

1. Index array subscripts are numbers called index arrays
2. The subscript of associative array is a string, which is called associative array (similar to the map type of ECMA6)
3. Global array
$_ get receives all data submitted through get
_ post receives all data submitted through post

The index array and associative array in the array can be combined with each other to form a multi-dimensional array.

Length of array count($cars) returns the length of the array

ajax

ajax asynchronous javascript and XML (data transfer format)
Asynchronous javascript and data transmission

[note] ajax is a porter for data interaction between front and back ends, which can be executed asynchronously.

xml data transmission format(

Large portal websites (Sina, Netease, Phoenix)
advantage:
1. Rich species
2. The transmission volume is very large
Disadvantages:
1. Analysis trouble
2. Not suitable for lightweight data

json data transfer format (string)

95% mobile applications.
advantage:
1. Lightweight data
2. Parsing is easy
Disadvantages:
1. There are few types of data
2. The amount of data transmitted is relatively small

JSON.parse()
JSON.stringify()

[note] any program is composed of many small programs.
[note] used to describe the running state of a program.
Synchronization blocking, the current program is running, and it can only run after the previous program is running.
Asynchronous and non blocking. The current program is running and has nothing to do with the previous program.

ajax loads data asynchronously

					//1. Creating ajax objects
                    var xhr = new XMLHttpRequest();
                    //2. Call open
                    /* 
                        First parameter: request method: get post
                        Second parameter: url
                        Third parameter: asynchronous  
                             true asynchronous
                             false synchronization
                     */
                    xhr.open("get", "1.txt", true);

                    //3. Call send
                    xhr.send();

                    //4. Waiting for data response
						/* 
                        readystatechange Event type
                        xhr.readyState  Called when changes occur
                        0  Before calling the open method
                        1  After calling your send method, send the request
                        2  send Method is completed, and all response contents have been accepted
                        3  Parsing downloaded data
                        4  Parsing complete
                     */
                    xhr.onreadystatechange = function(){
                        if(xhr.readyState == 4){
                            //Judge the status codes of this download
                            if(xhr.status == 200){
                                alert(xhr.responseText);
                            }else{
                                alert("Error:" + xhr.status);
                            }
                        }
                    }
ajax object compatibility: (if else)
					//ajax object compatibility
                    var xhr = null;
                    if(window.XMLHttpRequest){
                        xhr = new XMLHttpRequest();
                    }else{
                        xhr = new ActiveXObject("Microsoft.XMLHTTP");
                    }
ajax object compatibility: (try)
					//1. Creating ajax objects
                    var xhr = null;
                    try{
                        xhr = new XMLHttpRequest();
                    }catch(error){
                        xhr = new ActiveXObject("Microsoft.XMLHTTP");
                    }
Encapsulating ajax:

Status code:

200 - successful transaction

404 - no files, queries or URLs found

401 - authorization request failed

mysql

PHP connection database
<?php 
	header("Content-type:text/html;charset=utf-8");
	/*
		Link database Tianlong eight
	*/
	//1. Linked database
	/*
		The first parameter: the IP / domain name of the linked database
		Second parameter: user name
		Third parameter: password
	*/
	$link = mysql_connect("localhost", "root", "123456");
	//2. Judge whether the connection is successful
	if(!$link){
		echo "link failure";
		exit; //Terminate all subsequent codes
	}
	//3. Set character set
	mysql_set_charset("utf8");
	//4. Select database
	mysql_select_db("yyy");
	//5. Prepare sql statement
	$sql = "SELECT * FROM student";
	//6. Send sql statement
	$res = mysql_query($sql);
	//Set header
	echo "<table border = '1'>";
	echo "<tr><th>Student number</th><th>Student name</th><th>English achievement</th><th>Mathematics achievement</th><th>grade scores of Chinese<th></tr>";
	//7. Processing results
	while($row = mysql_fetch_assoc($res)){
		echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td>{$row['english']}</td><td>{$row['math']}</td><td>{$row['chinese']}</td></tr>";
	}
	echo "</table>";
	//8. Close database
	mysql_close($link);
 ?>

[note] ensure that the id is not repeated. Set the id as the primary key of the table and select the id as AI (automatically added)

Network protocol

computer network
Network layering of ISO layer 7
Common 5-layer network layering

The transmission of network data on the Internet complies with the transmission rules, which is called network transmission protocol.

TCP: link oriented protocol.

TCP is a connection oriented, reliable and byte stream based transport layer communication protocol. (express, takeout)

[note] if transmission is needed, first establish a link and start transmitting data. When the data transmission is completed, directly disconnect the link. If you want to transfer again, re-establish the link.

Three handshakes establish the connection and four waves disconnect the connection

Advantages: disadvantages:
1. Security 1. Low transmission efficiency
2. Very high accuracy 2. Resource consumption

UDP: connectionless protocol

UDP is the abbreviation of User Datagram Protocol. It is a connectionless transport layer protocol in the reference model, which provides simple and unreliable transaction oriented information transmission services. (applicable to high requirements for timeliness but low requirements for data accuracy)
Data transmission: direct transmission, regardless of whether data is received or not.

Disadvantages: advantages:
1. Unsafe 1. High timeliness
2. The accuracy is very low. 2. It consumes less resources
3. Frequent packet loss [note] video chat.

HTTP (stateless protocol)

cookie

cookie concept

Callback tracking technology: in the whole process from the beginning to the end of a session, track and record the status of the client (for example, whether to log in, shopping cart information, downloaded, liked, video playback progress, etc.)

cookie syntax

Format: name=value;[expires=date];[path=path];[domain=somewhere.com];[secure],
name key
value values are custom
[note] the contents of the following brackets (brackets are added by me) are optional.
[note] Firefox supports locally loaded file cache cookies, while Google only supports server loaded file cache cookies

cookie features

1. The expiration time can be set
2. It can store up to 4KB and up to 50 pieces of data under each domain name (different browsers, with deviation)
[note] only strings can be used. Generally, only some important information is stored. Login, shopping cart information, like or not, video playback progress, etc.

			/* 
                encodeURIComponent  Compile Chinese into corresponding characters
                decodeURIComponent  Compile the corresponding characters into Chinese
             */
              //Set cookie s
              document.cookie = 'username=' + encodeURIComponent("Iron Man");
              //Get cookie
              alert(decodeURIComponent(document.cookie));

Expires: expiration time. If it is not declared, it will become invalid after the browser is closed. If the expiration time is declared, it can not expire until the time expires.
Must be filled in, Date object
[note] the system will automatically clear expired cookie s.

Path restrict access path
If you don't set it, the default is to load the current Path to html file
[note] the path of the cookie we set must be consistent with the path of loading the current file. If it is inconsistent, the cookie access fails.

Domain restrict access to domain names
If you don't set it, the default is to load the current Server domain name / ip of html file
[note] if the domain name of the current file loaded is inconsistent with the set domain name, the cookie setting fails.

secure
If the cookie is not set, the file settings can be loaded through the http protocol
You can also load file settings through https protocol

[note] after setting this field, you can only set https protocol to load cookie s

https certificate authentication protocol
http

closure

Characteristics of closures:

1. Function nested function
2. The internal function refers to the variable or formal parameter to which the external function refers
3. The referenced variables or parameters will not be recycled by the garbage collection mechanism and will reside in memory.

Benefits:

1. You want a variable to reside in memory
2. Avoid global variable contamination
3. Private members can be declared

You can use variables that cannot be accessed from a domain

Modular development

1. Modular writing - original writing

A module is a set of methods to realize a specific function.
As long as different functions (and variables recording state) are simply put together, it can be regarded as a module.
For example: tool js

Disadvantages: "pollute" the global variables, so it is impossible to ensure that there is no variable name conflict with other modules, and there is no direct relationship between module members.

2.Javascript modular writing - object writing

Write the module as an object, and all module members are placed in this object.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ho7ujohp-1605075741267) (C: \ users \ administrator \ appdata \ roaming \ typora \ typora user images \ 1604630197591. PNG)]

3.Javascript modular writing method - immediate execution function writing method (closure)

Using execute function now (IIFE), you can achieve the purpose of not exposing private members.

External code cannot access internal variables

4.Javascript modular writing - zoom in mode

If a module is large and must be divided into several parts, or one module needs to inherit another module, it is necessary to adopt "amplification mode".

5.Javascript modular writing - wide magnification mode

In the browser environment, each part of the module is usually obtained from the Internet. Sometimes it is impossible to know which part will be loaded first. If the writing method in the previous section is adopted, the first execution part may load an empty object that does not exist. At this time, the "wide zoom in mode" should be adopted.

AMD

AMD is the abbreviation of "Asynchronous Module Definition", which means "Asynchronous Module Definition". It loads modules asynchronously, and the loading of modules does not affect the operation of subsequent statements. All statements that depend on this module are defined in a callback function. The callback function will not run until the loading is completed.

require.js

(1) Realize the asynchronous loading of js to avoid the loss of response of web pages

(2) Manage the dependencies between modules to facilitate code writing and maintenance

<script src = 'js/require.js' defer async = 'true' data-main = 'js/main.js' charset="big5">//Asynchronous loading under defer IE async = 'true' asynchronous entry files under Firefox and Google browser

The data main attribute is used to specify the main module of the web program. In the above example, it is main under the js directory js, this file will be required first js load. Due to require js the default file suffix is js, so you can put main js is abbreviated as main.

Writing method of main module

The main module depends on other modules. In this case, the require() function defined by AMD specification should be used.

require(["nav","slide","data"],function(nav,slide,data){}

The require() function takes two arguments. The first parameter is an array, which indicates the modules it depends on. The above example is ["nav", "slide", "data"], that is, the main module depends on these three modules; The second parameter is a callback function, which will be called when the previously specified modules are loaded successfully. The loaded modules will be passed into the function in the form of parameters, so that these modules can be used inside the callback function.
require() asynchronously loads NAV, slide and data, and the browser will not lose response; The callback function specified by it will run only after the previous modules are loaded successfully, which solves the problem of dependency.

Modular loading
require.config({
    paths:{
        "jquery": "jquery-1.11.3",
        "jquery-cookie": "jquery.cookie",//Setting dependencies jQuery cookies are developed through jQuery
        "nav":  "nav",
        "slide":"slide",
        "data":"data"
    }
    )}

Use require Config () method, we can customize the loading behavior of the module. require.config() is written in the header of the main module (main.js). Parameter is an object whose paths attribute specifies the loading path of each module.

require.js requires that each module is a separate js file. In this way, if multiple modules are loaded, multiple HTTP requests will be issued, which will affect the loading speed of the web page. Therefore, require js provides an optimization tool. After the module is deployed, you can use this tool to combine multiple modules into one file to reduce the number of HTTP requests.

AMD module writing

The module must be defined with a specific define() function. If a module does not depend on other modules, it can be defined directly in the define () function. If this module also depends on other modules, the first parameter of the define () function must be an array indicating the dependency of the module.

define(["jquery"],function($){})
AMD specification
 AMD Specification: (client)/(browser)
                Statement:
                    define(function(){
                        //code
                        return {
                            outA: showA,
                            outB: showB
                        }
                    })
                Introduction: (asynchronous execution)
                    require("moduleA.js", function(moduleA){

                        //Here's the code. Execute after module introduction.
                        moduleA.putA();
                        moduleA.outB();
                    })

                    alert("hello world");
Write code according to CommonJS specification (server)

				statement:
                    module.exports = {
                        outA: showA,
                        outB: showB
                    }
                Import: (synchronous execution)
                    var moduleA = require('moduleA.js');
                    moduleA.outA();
                    moduleA.outB();

Tags: PHP Front-end Database

Posted by phenley on Sun, 08 May 2022 09:05:26 +0300