PHP Getting Started Tutorial Lite Version_PHP Tutorial

WBOY
Release: 2016-07-21 15:42:46
Original
792 people have browsed it

Below, I, Green Apple, will take you on the road to getting started with PHP
Description:
I am currently using Apache web server and MY SQL as the WEB server and database, and the program is made in the environment of php-4.3.3 . Of course, PHPMYADMIN is indispensable for simply building and accessing the database
Here you need to know the basics of HTML! No basic knowledge of HTML! You can search on Baidu or GOOGLE! Very simple! Not much to say here
Okay, let’s get started! Let’s think of getting started with PHP as an apple! Eat him one bite at a time!
No more blabbering! Let’s start
Eat Apple 1
1. Embedding method:
Similar to ASP’s <%, PHP can be , of course you can also Specify it yourself.
2. Reference files:
There are two ways to reference files: require and include.
Require is used 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. Comment method:
echo "This is the first example. n" ; // This example is a comment on C++ syntax (PHP comments are similar to C!)
/* This example uses multi-line
comment method*/
echo "This is the second example. n";
echo "This is the third example. n"; # This example uses UNIX Shell syntax comments
?>
4. Variable type:
$mystring = "I am a string";
$NewLine = "Newline n";
$int1 = 38 ;
$float1 = 1.732 ;
$float2 = 1.4E+2 ;
$MyArray1 = array( "子" , "Chou" , "寅" , "卯" );
Exported here Two problems. 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. Arithmetic symbols:
Number**Illegal words have been blocked** Arithmetic:
Symbol meaning
+ Addition operation
- Subtraction operation
* Multiplication operation
/ Division operation
% Remainder
++ Accumulation
-- Decrement

String operation:
There is only one operation symbol, which is the English period. It can concatenate strings into new merged strings. Similar to &
$a = "PHP 4" in ASP;
$b = "Powerful";
echo $a.$b;
?>
This also leads to two questions. First, the output statement in PHP is echo. Second, it is similar to <%=variable%> in ASP. In PHP, it can also be .
Logical operations:
Symbol meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= is not equal to
&& and (And)
and and (And)
or (Or)
or or (Or)
xor Xor (Xor)
! Not ( Not)
Let’s talk about process control.
Learning purpose: Master the process control of PHP

1. There are three structures of if..else loops

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

if (expr) { statement }

where 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.

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

Special attention here is that judging whether they are equal is == Instead of =, 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.

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


The second type is to add an else condition in addition to if, 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 execution, there is no need to add curly brackets

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


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

Look at the following example directly

if ( $a > $b ) {
echo "a is bigger than b" ;
} elseif ( $a == $b ) {
echo "a is equal to 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.

for ( $i = 1 ; $i <= 10 ; $i ++) {
echo "This is the ".$i."th loop< ;br>" ;
}
?>

3. The 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 , 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.

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

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


Obviously, using the if loop in the above example is very troublesome. Of course, when designing, the conditions with the greatest probability of occurrence should be placed 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.

Learn to build a database

In PHP, the command line editing of MY SQL may be 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,
Language (*) Select Chinese Simplified 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. Create a new table in the database shop below

:
Name:
Number of fields:

Fill in the table name and the approximate number of fields you think (not enough or too many) It doesn’t matter, you can add it later or default it), 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:
We commonly use the following ones:
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 and modify the table structure
2) Press the browse on the right : View the data in the table
3) Press SQL on the right: Run the 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 ASP's ACCESS is simple. You can directly upload the MDB file. 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, press SQL after creating the database, and paste all the SQL statements generated by this level that you just copied.

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 the 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).而参数 hostname 后面可以加冒号与端口号,代表使用哪个端口与 MySQL 连接。当然在使用数据库时,早点使用 mysql_close() 将连接关掉可以节省资源。

2、 mysql_select_db

选择一个数据库。
语法: int mysql_select_db(string database_name, int [link_identifier]); 返回值: 整数

本函数选择 MySQL 服务器中的数据库以供之后的资料查询作业 (query) 处理。成功返回 true,失败则返回 false。

最简单的例子就是:
$conn=mysql_connect ("127.0.0.1", "", "");
mysql_select_db("shop");
连接机MY SQL数据库,打开SHOP数据库。在实际应用中应当加强点错误判断。


学会读取数据

先看两个函数:
1、mysql_query
送出一个 query 字符串。 语法: int mysql_query(string query, int [link_identifier]); 返回值: 整数

本函数送出 query 字符串供 MySQL 做相关的处理或者执行。若没有指定 link_identifier 参数,则程序会自动寻找最近打开的 ID。当 query 查询字符串是 UPDATE、INSERT 及 DELETE 时,返回的可能是 true 或者 false;查询的字符串是 SELECT 则返回新的 ID 值,当返回 false 时,并不是执行成功但无返回值,而是查询的字符串有错误。

2、mysql_fetch_object 返回类资料。 语法: object mysql_fetch_object(int result, int [result_typ]); 返回值: 类

本函数用来将查询结果 result 拆到类变量中。若 result 没有资料,则返回 false 值。

看一个简单的例子:
$exec="select * from user";
$result=mysql_query($exec);
while($rs=mysql_fetch_object($result))
{
echo "username:".$rs->username."
";
}
?>
当然,表user中有一个username的字段,这就类似asp中的
<%
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
%>
当然先要连接数据库,一般我们 require_once('conn.php');而conn.php里面就是上一次说的连接数据库的代码。

小小的两条命令可以完成读取数据的工作了


学会添加删除修改数据

mysql_query($exec);
单这个语句就可以执行所有的操作了,不同的就是$exec这个sql语句

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

删除:$exec="delete from tablename where...";

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

说到这里就要说一下表单和php变量传递,如果表单中的一个
表单以POST提交的,那么处理表单文件就可以用$_POST['item1']得到变量值,同样以GET提交的就是$_GET['item1']

是不是很简单?但是通常$exec会有问题,因为可能您的SQL语句会很长,您会遗漏.连接符,或者'来包围字符型字段。
我们可以注释mysql_query($exec);语句用echo $exec;代替来输出$exec以检查正确性。如果您还不能察觉$exec有什么错误的话,可以复制这个sql语句到phpmyadmin中执行,看看它的出错信息。还有需要注意的是,我们不要使用一些敏感的字符串作为字段名字,否则很可能会出现问题,比如说date什么的。变量的命名,字段的命名遵循一点规律有的时候对自己是一种好处,初学者并不可忽视其重要性。

学会SESSION的使用

SESSION的作用很多,最多用的就是站点内页面间变量传递。

在页面开始我们要session_start();开启SESSION;
然后就可以使用SESSION变量了,比如说要赋值就是:$_SESSION['item']="item1";要得到值就是$item1=$_SESSION['item'];,很简单吧。这里我们可能会使用到一些函数,比如说判断是不是某SESSION变量为空,可以这么写:empty($_SESSION['inum'])返回true or false。

下面综合一下前面所说的我们来看一个登陆程序,判断用户名密码是否正确。
登陆表单是这样:login.php




















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


做一个分页显示

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

对于$page如果没有我们就让它=0,如果有<0就让它也=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<0)$page=0;
if($page>=ceil($num/10))$page=ceil($num/10)-1;//因为page是从0开始的,所以要-1
}

这样$exec可以这么写 $exec="select * from tablename limit ".($page*10).",10";
//一页是10记录的

最后我们需要做的就是几个连接:
FirstPage
PrevPage
NextPage
LastPage

注意事项

1、注意不要漏了分号
2、注意不要漏了变量前的$
3、使用SESSION的时候注意不要遗漏session_start();

如果发生错误的时候,可以采用以下方法:
1、如果是SQL语句出错,就注释了然后输出SQL语句,注意也要注释调后续的执行SQL语句
2、如果是变量为空,大多是没有传递到位,输出变量检查一下,检查一下表单的id和name
3、如果是数据库连接出错,检查是否正确打开MY SQL和是否遗漏了连接语句
4、注意缩进,排除括号不区配的错误

在做大网站的时候,我的思路是先构建数据库,确定每一个字段的作用,和表之间的关系。然后设计后台界面,从添加数据开始做起,因为添加是否成功可以直接到数据库里面验证,做好了添加再做显示的页面,最后才是两者的结合。一般来说后台就包括添加删除修改和显示,后台没有问题了,前台也没有什么大问题。前台还需要注意安全性和容错还有就是输出格式。


学会用PHP上传文件和发邮件

上传文件表单必须加上 enctype="multipart/form-data"

下面看一下代码:

$f=&$HTTP_POST_FILES['file'];
$dest_dir='uploads';//设定上传目录
$dest=$dest_dir.'/'.date("ymd")."_".$f['name'];//我这里设置文件名为日期加上文件名避免重复
$r=move_uploaded_file($f['tmp_name'],$dest);
chmod($dest, 0755);//设定上传的文件的属性

上传的文件名为date("ymd")."_".$f['name'] ,可以在以后插入到数据库的时候用到,PHP实际上是把你上传的文件从临时目录移动到指定目录。move_uploaded_file($f['tmp_name'],$dest); This is the key

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

mail("recipient address" ,"Subject","Text","From: sender rnReply-to: sender's address");

However, mail() requires server support, and SMTP server needs to be configured under WINDOWS , Generally speaking, any 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.

That’s it for learning PHP. What I want to tell you is that it can take ten days to get started with PHP, but it definitely doesn’t take ten days to master it. You still need to do your own research and refer to other people’s codes to understand that it is not plagiarism. .

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320933.htmlTechArticleThe following instructions from Green Apple will take you to get started with PHP: I am currently using Apache web server and MY SQL is used as a WEB server and database, and is a program made in the environment of php-4.3.3. ...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!