search
HomeBackend DevelopmentPHP TutorialPHP Quick Tips, Quick Tips_PHP Tutorial

PHP quick fix, quick fix

A brief introduction to the syntax of PHP

1. Embedding method:

Similar to ASP's . Of course, you can also specify it yourself.

2. Referenced documents :

There are two ways to reference files: require and include.
The usage method of require is as require("MyRequireFile.php");. This function is usually placed at the front of the PHP program. Before the PHP program is executed, it will first read in the file specified by require and make it a part of the PHP program web page. Commonly used functions can also be introduced into web pages in this way.

include is used like include("MyIncludeFile.php"); . This function is generally placed in the processing part of flow control. The PHP program webpage only reads the include file when it reads it. In this way, the process of program execution can be simplified.

3. Annotation method :

Program code

Copy code The code is as follows:

echo "This is the first example. " ; // This example is a comment on C++ syntax
/* This example uses multi-line
Comment method */
echo "This is the second example. " ;
echo "This is the third example. " ; # This example uses UNIX Shell syntax comments
?>

4. Variable type :

Copy code The code is as follows:

$mystring = "I am a string" ;
$NewLine = "Line break" ;
$int1 = 38 ;
$float1 = 1.732 ;
$float2 = 1.4E+2 ;
$MyArray1 = array( "子" , "Chou" , "寅" , "卯" );

Two questions arise here. First, PHP variables start with $, and second, PHP statements end with ;. ASP programmers may not adapt to this. These two omissions are where most errors in the program lie.

5. Operation symbols :

Mathematical operations: Symbol Meaning
+ Addition
- Subtraction operation
* Multiplication
/ Division operation
% Take the remainder
++ Accumulate
-- Decreasing

String operations:

There is only one operator symbol, which is the English period. It can concatenate strings into new merged strings. Similar to &

in ASP

Program code

Copy code The code is as follows:


$a = "PHP 4" ;
$b = "Powerful" ;
echo $a.$b;
?>

Two questions also arise here. First, the output statement in PHP is echo. Second, it is similar to in ASP. In PHP, it can also be = variable?>.

Logical operations:

Symbol Meaning
> Greater than
>= greater than or equal to
== equals
!= is not equal to
&& And (And)
and And (And)
|| Or (Or)
or or (Or)
xor exclusive or (Xor)
! Not (Not)

Learning purpose: Master the process control of php

1. If..else loop has three structures

The first is to use only the if condition and treat it as a simple judgment. Interpreted as "what to do if something happens". The syntax is as follows:

if (expr) { statement }

The expr is the condition for judgment, usually using logical operation symbols as the condition for judgment. The statement is the execution part of the program that meets the conditions. If the program has only one line, the curly brackets {} can be omitted.

Example: This example omits the curly braces.

Program code

Copy code The code is as follows:

if ($state==1)echo "Haha" ;
?>

Special attention here is that == is used to determine whether they are equal, not =. ASP programmers may often make this mistake, = is assignment.

Example: The execution part of this example has three lines, and the curly brackets cannot be omitted.

Program code

Copy code The code is as follows:

if ($state==1) {
echo "Haha ;
echo "
" ;
}
?>

The second type is that in addition to if, an else condition is added, which can be interpreted as "what to do if something happens, otherwise how to solve it." The syntax is as follows

if (expr) { statement1 } else { statement2 } Example: Modify the above example into a more complete processing. Since there is only one line of instructions for executing else, there is no need to add braces.

Program code

Copy code The code is as follows:

if ($state==1) {
echo "Haha" ;
echo "
";
}
else{
echo "Hehe";
echo "
";
}
?>

The third type is the recursive if..else loop, which is usually used in various decision-making judgments. It combines several if..else statements for processing.

Look directly at the example below

Program code

Copy code The code is as follows:

if ( $a > $b ) {
echo "a is bigger than b" ;
} elseif ( $a == $b ) {
echo "a equals b" ;
} else {
echo "a is smaller than b" ;
}
?>

The above example only uses a two-level if..else loop to compare two variables a and b. When actually using this kind of recursive if..else loop, please use it with caution, because too many levels of loops can easily cause problems with the design logic, or missing braces, etc., can cause inexplicable problems in the program.

2. There is only one type of for loop , with no changes. Its syntax is as follows

for (expr1; expr2; expr3) { statement }

where expr1 is the initial value of the condition. expr2 is the condition for judgment, and logical operators are usually used as the condition for judgment. expr3 is the part to be executed after statement is executed. It is used to change the conditions for the next loop judgment, such as adding one, etc. The statement is the execution part of the program that meets the conditions. If the program has only one line, the curly brackets {} can be omitted.

The following example is written using a for loop.

Program code

Copy code The code is as follows:

for ( $i = 1 ; $i echo "This is the ".$i."th loop
" ;
}
?>

3. Switch loop usually handles compound conditional judgments. Each sub-condition is part of the case instruction. In practice, if many similar if instructions are used, it can be synthesized into a switch loop.

The syntax is as follows

switch (expr) { case expr1: statement1; break; case expr2: statement2; break; default: statementN; break; }

The expr condition is usually a variable name. The exprN after case usually represents the variable value. After the colon is the part to be executed that meets the condition. Be sure to use break to break out of the loop.

Program code

Copy code The code is as follows:

switch (date ( "D" )) {
case "Mon" :
echo "Today is Monday" ;
break;
case "Tue" :
echo "Today is Tuesday" ;
break;
case "Wed" :
echo "Today is Wednesday" ;
break;
case "Thu" :
echo "Today is Thursday" ;
break;
case "Fri" :
echo "Today is Friday" ;
break;
default:
echo "It's a holiday today" ;
break;
}
?>

What needs to be noted here is break; don’t omit it, default, omission is okay.

Obviously, using the if loop in the above example is very troublesome. Of course, when designing, you should put the conditions with the greatest probability of occurrence at the front and the conditions with the least occurrence at the end, which can increase the execution efficiency of the program. In the above example, since the probability of occurrence is the same every day, there is no need to pay attention to the order of the conditions.

Learning purpose: Learn to build a database

In ASP, if it is an ACCESS database, you can directly open ACCESS to edit the MDB file. If it is a SQL SERVER, you can open the Enterprise Manager to edit the SQL SERVER database. However, in PHP, the command line editing of MY SQL may It's very troublesome for beginners. It doesn't matter. You can download PHPMYADMIN and install it. You can rely on it to build and edit the database in the future.

Let’s talk about its use.
After entering phpmyadmin, we first need to create a database. Select Chinese Simplified Language (*) here, then create a new database on the left, fill in the database name here, and click Create.

Then select the created database in the drop-down menu on the left.

below

Create a new table in database shop:
Name:
Number of fields:

Fill in

with the table name and the approximate number of fields you think (it doesn’t matter if there are not enough or more, you can add them later or default them), and press Execute.
Then you can start creating the table.
The first column is the name of the field; the second column selects the field type:
The ones we commonly use are the following:
1) VARCHAR, text type
2) INT, integer type
3) FLOAT, floating point type
4) DATE, date type
5) You may ask, where is the automatically added ID? Just select the INT type and select auto_increment in the following extras.

After creating the table, you can see the table you created on the left. After clicking, you can:
1) Press the structure on the right: View the modified table structure
2) Press Browse on the right: View the data in the table
3) Press SQL on the right: Run SQL statement
4) Press insert on the right: insert a row of records
5) Press Clear on the right: delete all records in the table
6) Press delete on the right: delete table

Another very important function is import and export. When we have completed the program and database locally, we need to have a local mirror on the server. If it is ASP ACCESS, it is simple. Just upload the MDB file directly. Yes, if it is SQL SERVER, you can also connect to the remote server for import. Then you can export all SQL statements in MY SQL, go to PHPMYADMIN on the remote server, create the database, press SQL, and paste all the SQL statements generated by this level that you just copied.

Learning purpose: Learn to connect to the database

PHP is simply a function library. The rich functions make some parts of PHP quite simple. It is recommended that you download a PHP function manual so that you can always use it.

I will briefly talk about connecting to the MYSQL database.

1. mysql_connect

Open a MySQL server connection.
Syntax: int mysql_connect(string [hostname] [:port], string [username], string [password]); Return value: integer

This function establishes a connection to the MySQL server. All parameters can be omitted. When this function is used without any parameters, the default value of the hostname parameter is localhost, the default value of the username parameter is the owner of the PHP execution process, and the password parameter is an empty string (that is, there is no password). A colon and port number can be added after the parameter hostname to indicate which port to use to connect to MySQL. Of course, when using a database, using mysql_close() early to close the connection can save resources.

2. mysql_select_db

Select a database.
Syntax: int mysql_select_db(string database_name, int [link_identifier]); Return value: integer

This function selects the database in the MySQL server for subsequent data query processing (query). Returns true on success, false on failure.

The simplest example is:
$conn=mysql_connect ("127.0.0.1", "", "");
mysql_select_db("shop");
Connect to the MY SQL database and open the SHOP database. In practical applications, error judgment should be strengthened.

Learning purpose: Learn to read data

Let’s look at two functions first:
1. mysql_query
Send a query string. Syntax: int mysql_query(string query, int [link_identifier]); Return value: integer

This function sends the query string for MySQL to perform related processing or execution. If the link_identifier parameter is not specified, the program will automatically look for the most recently opened ID. When the query string is Update, Insert and Delete, the returned value may be true or false; when the query string is Select, a new ID value is returned. When false is returned, it does not mean that the execution is successful but there is no return value, but There is an error in the query string.

2. mysql_fetch_object returns class data . Syntax: object mysql_fetch_object(int result, int [result_typ]); Return value: Class

This function is used to split the query result result into a class variable. If result has no data, a false value is returned.

Look at a simple example:

Program code

Copy code The code is as follows:


$exec="select * from user";
$result=mysql_query($exec);
while($rs=mysql_fetch_object($result))
{
echo "username:".$rs->username."
";
}
?>

Of course, there is a username field in the user table, which is similar to

in asp

Program code

Copy code The code is as follows:

exec="select * from user"
set rs=server.createobject("adodb.recordset")
rs.open exec,conn,1,1
do while not rs.eof
response.write "username:"&rs("username")&"
"
rs.movenext
loop
%>

Of course, we need to connect to the database first. Generally, we require_once('conn.php'); and conn.php contains the code to connect to the database mentioned last time.

Learning purpose: Learn to add, delete and modify data

mysql_query($exec);
This statement alone can perform all operations. The difference is the $exec sql statement

Add: $exec="insert into tablename (item1,item2) values ​​('".$_POST['item1']."',".$_POST['item1'].")";

Delete: $exec="delete from tablename where...";

Modify: $exec="update tablename set item1='".$_POST['item1']."' where ...";

At this point, we have to talk about form and php variable transfer. If an
If the form is submitted by POST, then you can use $_POST['item1'] to get the variable value when processing the form file. Similarly, if it is submitted by GET, it is $_GET['item1']

Isn’t it very simple? But usually $exec will have problems, because your SQL statement may be very long, and you will miss the .connection character, or ' to surround the character field.
We can comment out the mysql_query($exec); statement and replace it with echo $exec; to output $exec to check for correctness. If you still can't detect any errors in $exec, you can copy this sql statement and execute it in phpmyadmin to see its error message. It should also be noted that we should not use some sensitive strings as field names, otherwise problems may occur, such as date and so on. It is sometimes good for you to follow a little rule when naming variables and fields. Beginners should not ignore its importance.

Learning purpose: Learn how to use SESSION

SESSION has many functions, the most commonly used one is the transfer of variables between pages within the site. At the beginning of the page we need session_start(); to open SESSION;
Then you can use the SESSION variable. For example, to assign a value: $_SESSION['item']="item1"; to get the value, $item1=$ _SESSION['item'];, it's very simple. Here we may use some functions, for example, to determine whether a SESSION variable is empty, you can write: empty($ _SESSION['inum']) returns true or false.

Let’s take a look at a login procedure based on what we said earlier to determine whether the username and password are correct.
The login form is like this: login.php

Program code

Copy code The code is as follows:




















Administrators Login
Username


Password






处理文件是这样

程序代码

复制代码 代码如下:


require_once('conn.php');
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$exec="select * from admin where username='".$username."'";
if($result=mysql_query($exec))
{
if($rs=mysql_fetch_object($result))
{
if($rs->password==$password)
{
$_SESSION['adminname']=$username;
header("location:index.php");
}
else
{
echo "<script>alert('Password Check Error!');location.href='login.php';</script>";
}
}
else
{
echo "<script>alert('Username Check Error!');location.href='login.php';</script>";
}
}
else
{
echo "<script>alert('Database Connection Error!');location.href='login.php';</script>";
}

?>

conn.php是这样:

程序代码

复制代码 代码如下:


$conn=mysql_connect ("127.0.0.1", "", "");
mysql_select_db("shop");
?>

由于 $_SESSION['adminname']=$username;我们可以这样写验证是否登陆语句的文件:checkadmin.asp

程序代码

复制代码 代码如下:


session_start();
if($_SESSION['adminname']==')
{
echo "<script>alert('Please Login First');location.href='login.php';</script>";
}
?>

学习目的:做一个分页显示

关键就是用到了SQL语句中的limit来限定显示的记录从几到几。我们需要一个记录当前页的变量$page,还需要总共的记录数$num

对于$page如果没有我们就让它=0,如果有

复制代码 代码如下:

$execc="select count(*) from tablename ";
$resultc=mysql_query($execc);
$rsc=mysql_fetch_array($resultc);
$num=$rsc[0];

这样可以得到记录总数
ceil($num/10))如果一页10记录的话,这个就是总的页数

所以可以这么写

复制代码 代码如下:

if(empty($_GET['page']))
{
$page=0;
}
else
{
$page=$_GET['page'];
if($page if($page>=ceil($num/10))$page=ceil($num/10)-1;//因为page是从0开始的,所以要-1
}

In this way, $exec can be written as $exec="select * from tablename limit ".($page*10).",10";
//One page contains 10 records

The last thing we need to do is a few connections:

Program code

Copy code The code is as follows:

This is a general idea. Can you think of how to optimize it?

Learning purpose: Things to note

Because I learned ASP first, I will find a lot of things that I need to adapt to when I do PHP.

1. Be careful not to miss a semicolon
2. Be careful not to miss the $
before the variable 3. When using SESSION, be careful not to omit session_start();

If an error occurs, you can use the following methods:
1. If there is an error in the SQL statement, comment it out and then output the SQL statement. Note that you should also comment out the subsequent execution of the SQL statement
2. If the variable is empty, most of it is not passed in place. Check the output variable and check the id and name of the form
3. If there is a database connection error, check whether MY SQL is opened correctly and whether the connection statement is missing
4. Pay attention to indentation and eliminate errors caused by mismatched brackets

When building a larger website, my idea is to build a database first and determine the role of each field and the relationship between the tables. Then design the backend interface, starting from adding data, because whether the addition is successful can be directly verified in the database, and then the page is displayed after adding it, and finally the combination of the two. Generally speaking, the backend includes addition, deletion, modification and display. There is no problem in the backend, and there is no big problem in the frontend. The front desk also needs to pay attention to security and fault tolerance as well as output format.

Learning purpose: Learn to use PHP to upload files and send emails

The file upload form must add enctype="multipart/form-data"
and
Take a look at the code below:

Copy code The code is as follows:

$f=&$HTTP_POST_FILES['file'];
$dest_dir='uploads';//Set the upload directory
$dest=$dest_dir.'/'.date("ymd")."_".$f['name'];//I set the file name here with the date plus the file name to avoid duplication
$r=move_uploaded_file($f['tmp_name'],$dest);
chmod($dest, 0755);//Set the attributes of the uploaded file

The name of the uploaded file is date("ymd")."_".$f['name'], which can be used when inserting into the database later. PHP actually saves the file you uploaded from the temporary directory. Move to the specified directory. move_uploaded_file($f['tmp_name'],$dest);This is the key

As for sending emails, it is even easier. You can use the mail() function

mail("recipient address", "subject", "text", "From: sender Reply-to: sender's address");

However, mail() requires server support. Under WINDOWS, you also need to configure an SMTP server. Generally speaking, an external LINUX space will work.
It seems that uploading files and sending emails is much simpler than ASP. You only need to call functions. ASP also needs to use different components of the server such as FSO, JMAIL and so on.

Will you be able to learn php soon? I hope you guys will like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/950897.htmlTechArticlePHP quick method, quick method briefly introduce the syntax of PHP 1. Embedding method: Similar to ASP's %, PHP can Is it php or is, the ending symbol is, of course you can also specify it yourself. 2. Quote...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor