Table of Contents
$num_of_calls. $txt
My Categories
Home php教程 php手册 菜鸟学习:动态网页PHP基础学习笔记

菜鸟学习:动态网页PHP基础学习笔记

Jun 21, 2016 am 09:01 AM
function gt lt nbsp title

1、  PHP片段四种表示形式。

标准tags:

short tags:      ?> 需要在php.ini中设置short _open_tag=on,默认是on

asp tags: 需要在php.ini中设置asp_tags=on,默认是off

script tags:

2、  PHP变量及数据类型

1)$variable  ,变量以字母、_开始,不能有空格

2)赋值$variable=value;

3)弱类型,直接赋值,不需要显示声明数据类型

4)基本数据类型:Integer,Double,String,Boolean,Object(对象或类),Array(数组)  

5)特殊数据类型:Resourse(对第三方资源(如数据库)的引用),Null(空,未初始化的变量)

3、  操作符

1)赋值操作符:=

2)算术操作符:+,-,*,/,%(取模)

3)连接操作符:. ,无论操作数是什么,都当成String,结果返回String

4)Combined Assignment Operators合计赋值操作符:+=,*=,/=,-=,%=,.=

5)Automatically Incrementing and Decrementing自动增减操作符:

(1)$variable+=1 $variable++;$variable-=1 $variable-,跟c语言一样,先做其他操作,后++或-

(2)++$variable,-$variable,先++或-,再做其他操作

6)比较操作符:= =(左边等于右边),!=(左边不等于右边),= = =(左边等于右边,且数据类型相同),>=,>,

7)逻辑操作符:|| ó or,&&óand,xor(当左右两边有且只有一个是true,返回true),!

4、  注释:

单行注释:// ,#

多行注释:/*  */

5、  每个语句以;号结尾,与java相同

6、  定义常量:define(“CONSTANS_NAME”,value)

7、  打印语句:print,与c语言相同

8、  流程控制语句

1)if语句:

(1)if(expression)

{

    //code to excute if expression evaluates to true

}

(2)if(expression)

      {

      }

     else

      {

      }

(3)if(expression1)

   {

}

elseif(expression2)

{

}

else

{

}

2)swich语句

switch ( expression )

{

     case result1:

         // execute this if expression results in result1

         break;

     case result2:

        // execute this if expression results in result2

        break;

     default:

       // execute this if no break statement

       // has been encountered hitherto

}

3)?操作符:

 ( expression )?returned_if_expression_is_true:returned_if_expression_is_false;
 

4)while语句:

(1) while ( expression )
{
      // do something
}
(2)do

  {

   // code to be executed

} while ( expression );

5)for语句:

    for ( initialization expression; test expression; modification expression ) {

   // code to be executed

}

6)break;continue

9、  编写函数

1)定义函数:

function function_name($argument1,$argument2,……) //形参

{

   //function code here;

}

2)函数调用

function_name($argument1,$argument2,……); //形参

3)动态函数调用(Dynamic Function Calls):

  1:

  2:

  3:

Listing 6.5

  4:

  5:

  6:

  7: function sayHello() {   //定义函数sayHello

  8:     print "hello
";

  9: }

 10: $function_holder = "sayHello";  //将函数名赋值给变量$function_holder

 11: $function_holder();  //变量$function_holder成为函数sayHello的引用,调用$function_holder()相当于调用sayHello

 12: ?>

 13:

 14:

4)变量作用域:

全局变量:

  1:

  2:

  3:

Listing 6.8

  4:

  5:

  6:

  7: $life=42;

  8: function meaningOfLife() {

9: global $life; 

/*在此处重新声明$life为全局变量,在函数内部访问全局变量必须这样,如果在函数内改变变量的值,将在所有代码片段改变*/

 10:      print "The meaning of life is $life
";

 11: }

 12: meaningOfLife();

 13: ?>

 14:

 15:

5)使用static

  1:

  2:

  3:

Listing 6.10

  4:

  5:

  6:

  7: function numberedHeading( $txt ) {

  8:      static $num_of_calls = 0;

  9:      $num_of_calls++;

 10:      print "

$num_of_calls. $txt

";

 11: }

 12: numberedHeading("Widgets");  //第一次调用时,打印$num_of_calls值为1

 13: print("We build a fine range of widgets

"); 

 14: numberedHeading("Doodads");  /*第一次调用时,打印$num_of_calls值为2,因为变量是static型的,static型是常驻内存的*/

 15: print("Finest in the world

");

 16: ?>

 17:

 18:

6) 传值(value)和传址(reference):

传值:function function_name($argument)

  1:

  2:

  3:

Listing 6.13

  4:

  5:

  6:

  7: function addFive( $num ) {

  8:      $num += 5;

  9: }

 10: $orignum = 10;

 11: addFive( &$orignum );

 12: print( $orignum );

 13: ?>

 14:

 15:

结果:10

传址:funciton function_name(&$argument)

  1:

  2:

  3:

Listing 6.14

  4:

  5:

  6:

  7: function addFive( &$num ) {

  8:      $num += 5;  /*传递过来的是变量$num的引用,因此改变形参$num的值就是真正改变变量$orignum物理内存中保存的值*/

  9: }

 10: $orignum = 10;

 11: addFive( $orignum );

 12: print( $orignum );

 13: ?>

 14:

 15:

结果:15

7)创建匿名函数:create_function(‘string1’,’string2’); create_function是PHP内建函数,专门用于创建匿名函数,接受两个string型参数,第一个是参数列表,第二个是函数的主体

  1:

  2:

  3:

Listing 6.15

  4:

  5:

  6:

  7: $my_anon = create_function( '$a, $b', 'return $a+$b;' );

  8: print $my_anon( 3, 9 );

  9: // prints 12

 10: ?>

 11:

 12:

8)判断函数是否存在:function_exists(function_name),参数为函数名

10、用PHP连接MySQL

1)连接:&conn=mysql_connect("localhost", "joeuser", "somepass");

2)关闭连接:mysql_close($conn);

3) 数据库与连接建立联系:mysql_select_db(database name, connection index);

4) 将SQL语句给MySQL执行:$result = mysql_query($sql, $conn); //增删改查都是这句

5) 检索数据:返回记录数:$number_of_rows = mysql_num_rows($result);

   将记录放入数组:$newArray = mysql_fetch_array($result);

   例子:

  1:   2: // open the connection
  3: $conn = mysql_connect("localhost", "joeuser", "somepass");
  4: // pick the database to use
  5: mysql_select_db("testDB",$conn);
  6: // create the SQL statement
  7: $sql = "SELECT * FROM testTable";
  8: // execute the SQL statement
  9: $result = mysql_query($sql, $conn) or die(mysql_error());
 10: //go through each row in the result set and display data
 11: while ($newArray = mysql_fetch_array($result)) {
 12:     // give a name to the fields
 13:     $id = $newArray['id'];
 14:     $testField = $newArray['testField'];
 15:     //echo the results onscreen
 16:     echo "The ID is $id and the text is $testField
";
 17: }
 18: ?>

11、接受表单元素:$_POST[表单元素名],

ó$_POST[user]

接受url中queryString中值(GET方式):$_GET[queryString]

12、转向其他页面:header("Location: http://www.webjx.com");

13、字符串操作:

1)explode(“-”,str)óJava中的splite

2)str_replace($str1,$str2,$str3) =>$str1要查找的字符串,$str2用来替换的字符串,$str3从这个字符串开始查找替换

3)substr_replace:

14、session:

1)打开session:session_start(); //也可以在php.ini设置session_auto_start=1,不必再每个script都写这句,但是默认为0,则必须要写。

2)给session赋值:$_SESSION[session_variable_name]=$variable;

3)访问session:$variable =$_SESSION[session_variable_name];

4)销毁session:session_destroy();

15、显示分类的完整例子:

1:

  2: //connect to database

  3: $conn = mysql_connect("localhost", "joeuser", "somepass")

  4:     or die(mysql_error());

  5: mysql_select_db("testDB",$conn) or die(mysql_error());

  6:

  7: $display_block = "

My Categories

  8:

Select a category to see its items.

";

  9:

 10: //show categories first

 11: $get_cats = "select id, cat_title, cat_desc from

 12:     store_categories order by cat_title";

 13: $get_cats_res = mysql_query($get_cats) or die(mysql_error());

 14:

 15: if (mysql_num_rows($get_cats_res)

 16:    $display_block = "

Sorry, no categories to browse.

";

 17: } else {

 18:

 19:    while ($cats = mysql_fetch_array($get_cats_res)) { //将记录放入变量$cats中

 20:$cat_id = $cats[id];

 21:$cat_title = strtoupper(stripslashes($cats[cat_title]));

 22:$cat_desc = stripslashes($cats[cat_desc]);

 23:

 24: $display_block .= "

 25: href=\"$_SERVER[PHP_SELF][U1] ?cat_id=$cat_id\">$cat_title

//点击此url,刷新本页,第28行读取cat_id,显示相应分类的条目

 26: 
$cat_desc

";

 27:

 28:if ($_GET[cat_id] == $cat_id) { //选择一个分类,看下面的条目

 29:    //get items

 30:    $get_items = "select id, item_title, item_price

 31:    from store_items where cat_id = $cat_id

 32:     order by item_title";

 33:    $get_items_res = mysql_query($get_items) or die(mysql_error());

 34:

 35:    if (mysql_num_rows($get_items_res)

 36:         $display_block = "

Sorry, no items in

 37:          this category.

";

 38:     } else {

 39:

 40:         $display_block .= "

    ";

     41:

     42:         while ($items = mysql_fetch_array($get_items_res)) {

     43:             $item_id = $items[id];

     44:             $item_title = stripslashes($items[item_title]);

     45:             $item_price = $items[item_price];

     46:

     47:             $display_block .= "

  •  48:              href=\"showitem.php?item_id=$item_id\">$item_title

     49:               (\$$item_price)";

    [U2]  50:         }

     51:

     52:         $display_block .= "

";

 53:    }

 54: }

 55:     }

 56: }

 57: ?>

 58:

 59:

 60:

My Categories

 61:

 62:

 63: print $display_block; ?>

 64:

 65:

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(); 
?>



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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

OOBELANGUAGE Error Problems in Windows 11/10 Repair OOBELANGUAGE Error Problems in Windows 11/10 Repair Jul 16, 2023 pm 03:29 PM

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

See all articles