1. while loop
In this lesson, we will continue to use PHP and MySQL to write some simple and useful pages. We started to display the data in the database from the database we created yesterday, but it will be slightly improved.
First, we use the following code to query the database content.
<Html>
<Body>
<? Php
$ Db = mysql_connect ("localhost", "root ");
Mysql_select_db ("mydb", $ db );
$ Result = mysql_query ("SELECT * FROM employees", $ db );
Echo "<table border = 1> ";
Echo "<tr> <td> Name </td> <td> position </td> </tr> ";
While ($ myrow = mysql_fetch_row ($ result )){
Printf ("<tr> <td> % s </td> </tr>", $ myrow [1], $ myrow [2], $ myrow [3]);
}
Echo "</table> ";
?>
</Body>
</Html>
You may have noticed that we have added some new things in this program. The most obvious is the while () loop. This loop means that as long as there are records in the database that are readable (using the mysql_fetch_row () function), the record is assigned to the variable $ myrow and then braces ({}) are executed ({}). Taking a closer look, this part is important.
Note the mysql_fetch_row () function. There is a small problem here. It returns an array and must access a field in it with an array subscript. The first field subscript is 0, the second is 1, and so on. It is too cumbersome to execute some complex queries.
Now let's take a closer look at the cyclical process. We have seen the first few lines of the program in the example of lesson 1. Then, in the while () loop, we read a record from the query results and assigned the record to the array $ myrow. Then, we use the printf function to display the data content on the screen. Then, the loop is executed repeatedly, and the next record is read and assigned to $ myrow. This continues until all records have been read.
One advantage of using the while () loop is that if the database query does not return any records, you will not receive the error message. When the loop statement is just executed, the loop condition is not met and no data is assigned to $ myrow. Then the program runs directly.
But if no data is returned for the query, how can we let the user know this? Maybe we should provide some related messages to users. This can be done. Let's take a look at how to do it.>
II. if-else
See the following program.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service