PHP/MySQL Three-Day Pass - Day 2 (Monday)_PHP Tutorial
一、 while循环
在这一课里,我们将会继续深入下去,使用PHP和MySQL来写出一些简单而有用的页面。我们从昨天创建的数据库开始,显示库中的数据,但是会再稍微加以润色。
首先,我们用下面的代码来查询数据库内容。
$#@60;html$#@62; $#@60;body$#@62; $#@60;?php $db = mysql_connect("localhost", "root"); mysql_select_db("mydb",$db); $result = mysql_query("SELECT * FROM employees",$db); echo "$#@60;table border=1$#@62; "; echo "$#@60;tr$#@62;$#@60;td$#@62;姓名$#@60;/td$#@62;$#@60;td$#@62;职位$#@60;/td$#@62;$#@60;/tr$#@62; "; while ($myrow = mysql_fetch_row($result)) { printf("$#@60;tr$#@62;$#@60;td$#@62;%s %s$#@60;/td$#@62;$#@60;td$#@62;%s$#@60;/td$#@62;$#@60;/tr$#@62; ", $myro w[1], $myrow[2], $myrow[3]); } echo "$#@60;/table$#@62; "; ?$#@62; $#@60;/body$#@62; $#@60;/html$#@62; |
您可能已经注意到,我们在这个程序里加进了一些新东西。最明显的是while()循环。该循环是说,只要数据库里还有记录可读(使用mysql_fetch_row()函数),那就把该记录赋给变量$myrow,然后执行大括号({})内的指令。仔细看一下这里,这部分是比较重要的。
我们应该注意一下mysql_fetch_row()函数。这里有一点小问题,它返回的是一个数组,必须以数组下标来访问其中的某个字段。第一个字段下标为0,第二个是1,依此类推。在执行某些复杂查询时,这么做简直实在是太烦琐了。
现在我们更仔细地研究一下循环过程。程序前几行我们在第一课的例子中已经看到过了。然后,在while()循环中,我们从查询结果中读取一条记录并把该记录赋给数组$myrow。接着,我们用printf函数把数据中的内容显示在屏幕上。随后,循环反复执行,读取下一条记录赋给$myrow。这样继续下去,直到所有记录都已被读取完为止。
使用while()循环? 个好处是,如果数据库查询没有返回任何记录,那您也不会收到错误信息。在刚执行循环语句时,循环条件就不满足,不会有任何数据赋给$myrow,程序就直接往下运行了。
但是如果查询未返回任何数据,我们怎么让用户知道这一点呢?我们也许该提供点儿相关的消息给用户吧。这是可以做到的,下面我们就看看怎么做。
二、 if-else
请看下面的程序。
$#@60;html$#@62; $#@60;body$#@62; $#@60;?php $db = mysql_connect("localhost", "root"); mysql_select_db("mydb",$db); $result = mysql_query("SELECT * FROM employees",$db); if ($myrow = mysql_fetch_array($result)) { echo "$#@60;table border=1$#@62; "; echo "$#@60;tr$#@62;$#@60;td$#@62;姓名$#@60;/td$#@62;$#@60;td$#@62;住址$#@60;/td$#@62;$#@60;/tr$#@62; "; do { printf("$#@60;tr$#@62;$#@60;td$#@62;%s %s$#@60;/td$#@62;$#@60;td$#@62;%s$#@60;/tr$#@62; ", $myrow["first"], $myrow["last"], $myrow["address"]); } while ($myrow = mysql_fetch_array($result)); echo "$#@60;/table$#@62; "; } else { echo "对不起,没有找到记录!"; } ?$#@62; $#@60;/body$#@62; $#@60;/html$#@62; |
这段程序中包含有不少新内容,不过这些内容都相当简单。首先是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方法;第二种是在浏览器的地址栏中输入网址时直接加上查询参数;第三种是把查询参数串嵌入到网页的超链接中,使得超链接的内容象下面这样:$#@60;a href="http://my_machine/mypage.php3?id=1"$#@62;。我们现在要用到最后这一种方法。
一开始,我们再来查询我们的数据库,列出员工姓名。看看下面的程序,其中大部分内容我们都已经很熟悉了。
$#@60;html$#@62; $#@60;body$#@62; $#@60;?php $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("$#@60;a href="%s?id=%s"$#@62;%s %s$#@60;/a$#@62;$#@60;br$#@62; ", $PATH_INFO, $myrow["id"], $myrow["first"], $myrow["last"]); } while ($myrow = mysql_fetch_array($result)); } else { echo "对不起,没有找到记录!"; } ?$#@62; $#@60;/body$#@62; $#@60;/html$#@62; |
Nothing special here, just the printf function is a little different. So let’s take a closer look.
The first thing to note is that all quotation marks are preceded by a backslash. This backslash tells PHP to display the following characters directly instead of treating them as program code. Also pay attention to the usage of the variable $PATH_INFO. This variable is accessible in all programs and is used to save the name and directory location of the program itself. The reason why we use it is because we need to call the program itself in the page. Using $PATH_INFO, we can ensure that even if the program is moved to other directories or even on other machines, we can ensure that the program is called correctly.
As I just mentioned, the hyperlinks contained in the web pages generated by the program will call the program itself again. However, when called again, some query parameters will be added.
When PHP sees that the query parameter string contains a pair format such as "name=value", it will do some special processing. It will automatically generate a variable with the same name and value as those given in the query parameter string. This function allows us to determine whether the program is executed for the first time or the second time in the program. All we have to do is ask PHP if the $id variable exists.
Once I know the answer to this question, I can display some different results the second time I call the program. Please see:
$#@60;html$#@62; $#@60;body$#@62; $#@60;?php $db = mysql_connect("localhost", "root"); mysql_select_db("mydb",$db); // display individual record // Display the content of a single record if ($id) { $result = mysql_query("SELECT * FROM employees WHERE id=$id",$db); $myrow = mysql_fetch_array( $result); printf("Name: %s $#@60;br$#@62;", $myrow["first"]); printf("Last name: %s $#@60;br$#@62;", $myrow["last"]); printf("Address: %s $#@60;br$#@62;", $myrow["address"]); p |

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

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.

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

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

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.
