In PHP programming, displaying database data is generally done using a loop body. Commonly used methods include while() and for() statements. Let’s talk about their usage in different situations.
while use:
The while() statement can display all data, which is especially convenient when the number of loops is unknown. The for() statement can output and display data starting from the specified position to the specified position. The output displays a certain This is useful for range of data. Let’s take a look at a programming example:
Let’s first create a database for backup: database name: mydb and table name: tbl.
Use the following statement: create table tal (idx int(3),url char (100),freetext char(100))
You can use the phpmyadmin tool to insert several data into the database table.
Programming starts:
$id=MySQL_connect("localhost") or die("Unable to establish database link");#Link database
$result=mysql_db_query("mydb","select * from tbl",$id);#Query results and store them in variables
$rows=mysql_num_rows($result);#Get the total number of rows in the data table, which is the total number of data
echo"
";#Prepare to output in table form
echo "
";#End of table
for use:
Insert output statements in the above two sentences, corresponding to different situations, the output statements are divided into several situations:
If you want to output all the data, use for() first
for($i=0;$i<$rows;$i++){
$total=mysql_fetch_array($result);
echo "
$total[freetext]$total[idx]< /tr> | ";
}
Use while() to do
while($total=mysql_fetch_array($result))
{ echo "
$total[freetext]$total[idx]< ;/tr> | ";
}
When we want to display in pages, that is, we cannot display all the data at once, then we can use for() to complete this task.
We assume that every time 10 data are output, $page is used to represent the current page number. $pagesize=10 is used to represent the number of data on page. The statement is as follows:
for ($i=0;$i<$pagesize;$i++)
{
$start=($page-1)*$pagesize+$i;#Count the starting number of data rows
if ($start<$rows)
$idx=mysql_result($result,$start,"idx");
$url=mysql_result($result,$start,"url");
$freetext=mysql_result($result,$start,"freetext");
echo "
$freetext$idx |
";
The above statement uses for() to obtain the values of each field in the data table and stores them in variables, and uses the echo statement to display them.
The above program runs successfully in apache+mysql+php4
The above has introduced a comparison of several methods of displaying data in PHP, including the content of displaying data in PHP. I hope it will be helpful to friends who are interested in PHP tutorials.