Home php教程 php手册 PHP_MySQL教程-第二天while循环与数据库操作第1/2页

PHP_MySQL教程-第二天while循环与数据库操作第1/2页

Jun 13, 2016 pm 12:32 PM
mysql php while and cycle operate Tutorial database

第一页 while循环 
在这一课里,我们将会继续深入下去,使用PHP和MySQL来写出一些简单而有用的页面。我们从昨天创建的数据库开始,显示库中的数据,但是会再稍微加以润色。 
首先,我们用下面的代码来查询数据库内容。

复制代码 代码如下:


 

 
$db = mysql_connect("localhost", "root"); 
mysql_select_db("mydb",$db); 
$result = mysql_query("SELECT * FROM employees",$db); 
echo "n"; 
echo "n"; 
while ($myrow = mysql_fetch_row($result)) { 
    printf("n", $myrow[1], $myrow[2], $myrow[3]); 

echo "
姓名 职位
%s %s %s
n"; 
?> 
 
  

您可能已经注意到,我们在这个程序里加进了一些新东西。最明显的是while()循环。该循环是说,只要数据库里还有记录可读(使用mysql_fetch_row()函数),那就把该记录赋给变量$myrow,然后执行大括号({})内的指令。仔细看一下这里,这部分是比较重要的。 
我们应该注意一下mysql_fetch_row()函数。这里有一点小问题,它返回的是一个数组,必须以数组下标来访问其中的某个字段。第一个字段下标为0,第二个是1,依此类推。在执行某些复杂查询时,这么做简直实在是太烦琐了。 
现在我们更仔细地研究一下循环过程。程序前几行我们在第一课的例子中已经看到过了。然后,在while()循环中,我们从查询结果中读取一条记录并把该记录赋给数组$myrow。接着,我们用printf函数把数据中的内容显示在屏幕上。随后,循环反复执行,读取下一条记录赋给$myrow。这样继续下去,直到所有记录都已被读取完为止。 
使用while()循环的一个好处是,如果数据库查询没有返回任何记录,那您也不会收到错误信息。在刚执行循环语句时,循环条件就不满足,不会有任何数据赋给$myrow,程序就直接往下运行了。 
但是如果查询未返回任何数据,我们怎么让用户知道这一点呢?我们也许该提供点儿相关的消息给用户吧。这是可以做到的,下面我们就看看怎么做。>>

第二页 if-else 
请看下面的程序。

复制代码 代码如下:


 

 
$db = mysql_connect("localhost", "root"); 
mysql_select_db("mydb",$db); 
$result = mysql_query("SELECT * FROM employees",$db); 
if ($myrow = mysql_fetch_array($result)) { 
  echo "n"; 
  echo "n"; 
  do { 
    printf("n", $myrow["first"],  
$myrow["last"], $myrow["address"]); 
  } while ($myrow = mysql_fetch_array($result)); 
    echo "
姓名 住址
%s %s %s
n"; 
} else { 
    echo "对不起,没有找到记录!";     


?> 

 
  

这段程序中包含有不少新内容,不过这些内容都相当简单。首先是mysql_fetch_array()函数。该函数与mysql_fetch_row()十分相近,只有一点不同:使用这个函数时,我们可以通过字段名而不是数组下标来访问它返回的字段,比如$myrow["first"]。这样我们就可以省不少力气了。另外,程序中还加进了do/while循环和if-else条件判定语句。 
if-else条件判定语句的含意是,如果我们成功地把一条记录赋给了$myrow变量,那就继续;否则,就跳到else部分,执行那里的指令。 
do/while循环是我们在上页中用户的while()循环的一个变体。我们要用到do/while的原因是:在最初的if语句中,我们已经把查询返回的第一条记录赋给变量$myrow了。如果这时我们执行一般的while循环(比如,while ($myrow = mysql_fetch_row($result)),那我们就会把第二条记录赋给$myrow,而第一条记录就被冲掉了。但是do/while循环可以让我们执行一次循环体内容之后再来判定循环条件。因此,我们就不会不小心漏掉第一条记录了。 
最后,如果查询结果没有任何记录的话,程序就会执行包含在else{}部分的那些语句。如果您想看到这部分程序的执行情况,可以把SQL语句改为SELECT * FROM employees WHERE id=6,或改成其他形式,使得查询结果中没有任何记录。 
下面我们来扩充一下循环if-else 代码,使得页面内容更加丰富。相信您会喜欢的。

第三页 第一个程序脚本 
我们刚刚学到了循环语句,下面我们将在一个更加实际一点的例子中看看如何运用它。但是在这之前,您应该知道如何处理Web表格、查询参数串,以及表单的GET方法和POST方法。不久之前我们刚刚有文章介绍这部分内容,您如果对这一部分还不太熟悉的话可以看看那篇文章。 
现在,我们要处理查询参数串,正如您所知道的,有三种方法可以把参数内容写入到查询参数串中。第一种是在表格中使用GET方法;第二种是在浏览器的地址栏中输入网址时直接加上查询参数;第三种是把查询参数串嵌入到网页的超链接中,使得超链接的内容象下面这样:。我们现在要用到最后这一种方法。 
一开始,我们再来查询我们的数据库,列出员工姓名。看看下面的程序,其中大部分内容我们都已经很熟悉了。

复制代码 代码如下:


 

 
$db = mysql_connect("localhost", "root"); 
mysql_select_db("mydb",$db); 
$result = mysql_query("SELECT * FROM employees",$db); 
if ($myrow = mysql_fetch_array($result)) { 
  do { 
    printf("
%s %s
n",  
    $PATH_INFO, $myrow["id"], $myrow["first"], $myrow["last"]); 
  } while ($myrow = mysql_fetch_array($result)); 
} else { 
  echo "对不起,没有找到记录!";     

?> 
 
  


这里没什么特别的,只是printf函数有些不同。那我们就来仔细研究一下。 
首先要注意的是,所有的引号前面都有一个反斜杠。这个反斜杠告诉PHP直接显示后面的字符,而不能把后面的字符当作程序代码来处理。另外要注意变量$PATH_INFO的用法。该变量在所用程序中都可以访问,是用来保存程序自身的名称与目录位置的。我们之所以用到它是因为要在页面中再调用这个程序本身。使用$PATH_INFO,我们可以做到,即使程序被挪到其他目录,甚至是其他机器上时,我们也能保证正确地调用到这个程序。 
正如我刚才提到的,程序所生成的网页,其中包含的超链接会再次调用程序本身。不过,再次调用时,会加入一些查询参数。 
PHP见到查询参数串中包含有“名字=值”这样的成对格式时,会作一些特别的处理。它会自动生成一个变量,变量名称与取值都与查询参数串中所给定的名称和取值相同。这一功能使得我们可以在程序中判断出是第一次执行本程序还是第二次。我们所要做的只是问问PHP$id这个变量是否存在。 
当我知道这个问题的答案后,我可以在第二次调用程序时显示一些不同的结果出来。请看:

复制代码 代码如下:


 

 
$db = mysql_connect("localhost", "root"); 
mysql_select_db("mydb",$db); 
// display individual record 
// 显示单条记录内容 
if ($id) { 
   $result = mysql_query("SELECT * FROM employees WHERE id=$id",$db); 
   $myrow = mysql_fetch_array($result); 
   printf("名: %sn
", $myrow["first"]); 
   printf("姓: %sn
", $myrow["last"]); 
   printf("住址: %sn
", $myrow["address"]); 
   printf("职位: %sn
", $myrow["position"]); 
} else { 
    // show employee list 
    // 显示员工列表 
   $result = mysql_query("SELECT * FROM employees",$db); 
    if ($myrow = mysql_fetch_array($result)) { 
      // display list if there are records to display 
      // 如果有记录,则显示列表 
      do { 
        printf("%s %s
n", $PATH_INFO,  
        $myrow["id"], $myrow["first"], $myrow["last"]); 
      } while ($myrow = mysql_fetch_array($result)); 
    } else { 
      // no records to display 
      // 没有记录可显示 
      echo "对不起,没有找到记录!";     
    } 

?> 
 
  
程序开始变得复杂了,所以我在这里面加了注释,来解释一下到底发生了什么。您可以用//加入单行注释,或者用/*和*/来括住大段的注释。 
到这里,我们已经学会了第一个真正有用的PHP/MySQL脚本程序!现在,我们要看看怎样把Web表格加进来,并且向数据库发送数据。

第四页 向服务器发送数据 
现在我们从数据库读取数据已经没有太多困难了。但是怎么反过来向数据库发送数据呢?其实这不是PHP的问题。 
首选,我们创建一个带有简单表格的网页。

复制代码 代码如下:


 

 
"> 
名:
姓:
住址:
职位:
 
 
 
  

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1674
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

What are the advantages of using MySQL over other relational databases? What are the advantages of using MySQL over other relational databases? May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How to analyze the execution plan of MySQL query How to analyze the execution plan of MySQL query Apr 29, 2025 pm 04:12 PM

Use the EXPLAIN command to analyze the execution plan of MySQL queries. 1. The EXPLAIN command displays the execution plan of the query to help find performance bottlenecks. 2. The execution plan includes fields such as id, select_type, table, type, possible_keys, key, key_len, ref, rows and Extra. 3. According to the execution plan, you can optimize queries by adding indexes, avoiding full table scans, optimizing JOIN operations, and using overlay indexes.

See all articles