Home Backend Development PHP Tutorial A good PHP basic study note_PHP tutorial

A good PHP basic study note_PHP tutorial

Jul 21, 2016 pm 03:56 PM
php No Base study standard fragment notes express

1. Four representation forms of PHP fragments.
Standard tags:
short tags: You need to set short _open_tag=on in php.ini, the default is on >Need to set asp_tags=on in php.ini, the default is off
script tags:
2. PHP variables and data types
1) $variable, variables start with letters, _, and cannot have spaces
2) Assignment $variable=value;
3) Weak type, direct assignment, no need to display the declared data type
4) Basic data Type: Integer, Double, String, Boolean, Object (object or class), Array (array)
5) Special data types: Resource (reference to third-party resources (such as database)), Null (empty, uninitialized) Variables)
3. Operators
1) Assignment operators: =
2) Arithmetic operators: +, -, *, /, % (modulo)
3) Connection operators :., no matter what the operand is, it will be treated as String, and the result will be returned String
4) Combined Assignment Operators total assignment operators: +=, *=, /=, -=, %=, .=
5 ) Automatically Incrementing and Decrementing automatic increase and decrease operators:
(1)$variable+=1 <=>$variable++;$variable-=1 <=>$variable-, just like c language, do it first For other operations, follow ++ or -
(2) ++$variable, -$variable, first ++ or -, and then do other operations
6) Comparison operator: = = (left side is equal to right side), != (the left side is not equal to the right side), = = (the left side is equal to the right side, and the data type is the same), >=, >, <, <=
7) Logical operators: || ó or, &&óand , xor (when one and only one of the left and right sides is true, return true),!
4. Comments:
Single-line comments: //, #
Multi-line comments: /* */
5 , Each statement ends with ;, the same as java
6. Define constants: define("CONSTANS_NAME",value)
7. Print statement: print, the same as c language
8. Process control statement
1) If statement:
(1) if(expression)
{
//code to excute if expression evaluates to true
}
(2) if(expression)
{
}
else
{
}
(3)if(expression1)
{
}
elseif(expression2)
{
}
else
{
}
2) swich statement
switch (expression)
{
case result
// execute this if expression results in result1
break;
case result
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}
3) ? Operator:
(expression)?returned_if_expression_is_true:returned_if_expression_is_false;
4) while statement:
(1) while (expression)
{
// do something
}
(2) do
{
// code to be executed
} while (expression);
5) for statement:
for (initialization expression; test expression; modification expression) {
// code to be executed
}
6) break; continue
9. Write function
1) Define function:
function function_name($argument1,$argument2,……) //Formal parameters
{
//function code here;
}
2) Function call
function_name($argument1,$argument2,……); //Formal parameters
3) Dynamic Function Calls:


Listing 6.5


function sayHello() { //Define function sayHello
print "hello
";
}
$function_holder = "sayHello"; //Assign the function name to the variable $function_holder
$function_holder(); //The variable $function_holder becomes a reference to the function sayHello. Calling $function_holder() is equivalent to calling sayHello
? >


4) Variable scope:
Global variables:


Listing 6.8


$life=42;
function meaningOfLife() {
global $life;
/*Redeclare $life as a global variable here. Accessing global variables within a function must be done this way. If the value of the variable is changed within the function, it will be changed in all code fragments*/
print "The meaning of life is $life
";
}
meaningOfLife();
?>


5) Use static


Listing 6.10


function numberedHeading( $txt ) {
static $num_of_calls = 0;
$num_of_calls++;
print "

$num_of_calls. $txt

";
}
numberedHeading("Widgets"); //When called for the first time, print $num_of_calls value is 1
print("We build a fine range of widgets

");
numberedHeading("Doodads"); /*When called for the first time, print $num_of_calls value is 2, because the variable is static type, static type is resident in memory*/
print("Finest in the world?>


6) Passing value (value) and passing reference (reference):
Passing value: function function_name($argument)


Listing 6.13


function addFive( $num ) {
$num += 5;
}
$orignum = 10;
addFive( &$orignum );
print ( $orignum );
?>


Result: 10
Address: funciton function_name(&$argument)
< ;html>

Listing 6.14


function addFive( &$num ) {
$num += 5; /*What is passed is a reference to the variable $num, so changing the value of the formal parameter $num is actually changing the value stored in the physical memory of the variable $orignum*/
}
$orignum = 10;
addFive( $orignum );
print( $orignum );
?>


Result: 15
7) Create an anonymous function: create_function('string1','string2'); create_function is a built-in function in PHP, specially used to create anonymous functions. It accepts two string parameters, the first one is the parameter List, the second one is the body of the function


Listing 6.15

< body>
$my_anon = create_function( '$a, $b', 'return $a+$b;' );
print $my_anon( 3, 9 );
// prints 12
?>


8) Determine whether the function exists: function_exists(function_name), the parameter is the function name
10, Use PHP to connect to MySQL
1) Connection: &conn=mysql_connect("localhost", "joeuser", "somepass");
2) Close the connection: mysql_close($conn);
3) Database and connection Establish a connection: mysql_select_db(database name, connection index);
4) Execute the SQL statement to MySQL: $result = mysql_query($sql, $conn); //Add, delete, modify and check are all like this
5) Retrieve data: Return the number of records: $number_of_rows = mysql_num_rows($result);
Put the records into the array: $newArray = mysql_fetch_array($result);
Example:
/ / open the connection
$conn = mysql_connect("localhost", "joeuser", "somepass");
// pick the database to use
mysql_select_db("testDB",$conn);
// create the SQL statement
$sql = "SELECT * FROM testTable";
// execute the SQL statement
$result = mysql_query($sql, $conn) or die(mysql_error()) ;
//go through each row in the result set and display data
while ($newArray = mysql_fetch_array($result)) {
// give a name to the fields
$id = $ newArray['id'];
$testField = $newArray['testField'];
//echo the results onscreen
echo "The ID is $id and the text is $testField
";
}
?>
11. Accept form elements: $_POST[form element name],
such asó$_POST[user]
Accept the queryString value in the URL (GET method): $_GET[queryString]
12. Go to other pages: header("Location: http://www.samspublishing.com");
13. Characters String operations:
1) explode(“-”,str)ósplite in Java
2) str_replace($str1,$str2,$str3) =>$str1 is the string to be found, $str2 is used To replace the string, $str3 starts to search and replace from this string
3) substr_replace:
14. session:
1) Open session: session_start(); // It can also be set in php.ini session_auto_start=1, you don’t need to write this sentence in every script, but the default is 0, so you must write it.
2)给session赋值:$_SESSION[session_variable_name]=$variable;
3)访问session:$variable =$_SESSION[session_variable_name];
4)销毁session:session_destroy();
15、显示分类的完整例子:
//connect to database
$conn = mysql_connect("localhost", "joeuser", "somepass")
or die(mysql_error());
mysql_select_db("testDB",$conn) or die(mysql_error());
$display_block = "

My Categories


Select a category to see its items.

";
//show categories first
$get_cats = "select id, cat_title, cat_desc from
store_categories order by cat_title";
$get_cats_res = mysql_query($get_cats) or die(mysql_error());
if (mysql_num_rows($get_cats_res) < 1) { //如果返回记录行数小于1,则说明没有分类
$display_block = "

Sorry, no categories to browse.

";
} else {
while ($cats = mysql_fetch_array($get_cats_res)) { //将记录放入变量$cats中
$cat_id = $cats[id];
$cat_title = strtoupper(stripslashes($cats[cat_title]));
$cat_desc = stripslashes($cats[cat_desc]);
$display_block .= "

href="$_SERVER[PHP_SELF][U1] ?cat_id=$cat_id">$cat_title//点击此url,刷新本页,第28行读取cat_id,显示相应分类的条目

$cat_desc

";
if ($_GET[cat_id] == $cat_id) { //选择一个分类,看下面的条目
//get items
$get_items = "select id, item_title, item_price
from store_items where cat_id = $cat_id
order by item_title";
$get_items_res = mysql_query($get_items) or die(mysql_error());
if (mysql_num_rows($get_items_res) < 1) {
$display_block = "

Sorry, no items in
this category.

";
} else {
$display_block .= "
    ";
    while ($items = mysql_fetch_array($get_items_res)) {
    $item_id = $items[id];
    $item_title = stripslashes($items[item_title]);
    $item_price = $items[item_price];
    $display_block .= "
  • href="showitem.php?item_id=$item_id">$item_title
     ($$item_price)";
    [U2]                   }
    $display_block .= "
";
}
}
}
}
?>


My Categories





16、PHP连接Access:
$dbc=new com("adodb.connection");  
$dbc->open("driver=microsoft access driver (*.mdb);dbq=c:member.mdb");  
$rs=$dbc->execute("select * from tablename");  
$i=0;  
while (!$rs->eof){  
$i+=1  
$fld0=$rs->fields["UserName"];  
$fld0=$rs->fields["Password"]; 
....  
echo "$fld0->value $fld1->value ....";  
$rs->movenext();  
}  
$rs->close();  
?> 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/318111.htmlTechArticle1、PHP片段四种表示形式。 标准tags:?php? shorttags:??需要在php.ini中设置short_open_tag=on,默认是on asptags:%%需要在php.ini中设置asp_tags=on,默认是...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles