1. while loop in this lesson, we will continue to write some simple and useful pages using PHP and MySQL. From the beginning of the database we created yesterday, we will display the data in the database, but we will polish it a little more. First, I. 1. while loop
In this lesson, we will continue to use PHP and MySQL to write some simple and useful pages. From the beginning of the database we created yesterday, we will display the data in the database, but we will polish it a little more.
First, we use the following code to query the database content.
$ Db = mysql_connect ('localhost', 'root ');
Mysql_select_db ('mydb', $ db );
$ Result = mysql_query ('select * FROM employees ', $ db );
Echo'
\ N ';Echo'
| Name |
Position |
\ N ';While ($ myrow = mysql_fetch_row ($ result )){Printf ('
| % S |
% S |
\ N', $ myroW [1], $ myrow [2], $ myrow [3]);}Echo'
\ N ';
?>
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 the braces ({}) are executed ({}). Taking a closer look, this part is more important.
Take note of the mysql_fetch_row () function. There is a small title here. it returns an array and must use an array subscript to visit a field. The first field subscript is 0, the second is 1, and so on. When performing some complex queries, it is too cumbersome to do so.
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 repeats and the next record is read and assigned to $ myrow. This continues until all records have been read.
One benefit of the while () loop is that you will not receive an error message if no records are returned for database queries. 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 coherent messages to users. This can be done. let's take a look at how to do it.>
II. if-else
See the following program.
$ 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'
| Name |
Address |
\ N ';