Take a closer look at using mysql_fetch_row of to return query results as arrays

  • 2020-06-03 06:10:33
  • OfStack

Like mysql_result()1, mysql_fetch_row() can also be used to get a query result set, unlike a function that returns an array instead of a string. The function is defined as follows.

array mysql_fetch_row(int result) 

The parameters are described below.
result: Identified by the result returned by the functions mysql_query() or mysql_db_query() and used to specify the type of SQL statement for the data to be fetched.
The function returns the following values.
Success: 1 array containing the current row data information in the query result set, array index range 0 ~ record number of attributes − 1. The i element value in the array is the value on the i attribute of the record.
Failure: false.
mysql_fetch_row() below USES the sample functionality as shown in 5.5.1.

1    <!------ use mysql_fetch_row() To obtain data: mysql_fetch_row.php------>
2    <?php
3        // Connect and select to the database server 
4        $connection = mysql_connect ("localhost", "root", "password");
5        mysql_select_db("Books", $connection);
6        // Query data 
7        $query="SELECT * FROM Computers ";
8        $query.="WHERE price >= 20";
9        //echo $query."<br>";
10       $result=mysql_query($query,$connection);
11       // with mysql_fetch_row() Get the data and output it 
12       while($row=mysql_fetch_row($result))
13       {
14            echo " Title:     ".$row[1]."<br>";
15            echo " Price:     ".$row[2]."<br>";
16            echo " Publication Date:     ".$row[3]."<br>";
17            echo "<br>";
18       }
19   ?>

mysql_fetch_row() gets the data information for the current row and automatically slides to the next row when referenced. In this example, the reference to it in line 12 is:


In this loop, every time mysql_fetch_row() gets the current row, assigns a value to the array $row, and slides down to the next row; After fetching the last 1 line, the function returns false, and the loop ends. In this way, all the data in the result set can be fetched and displayed line by line.
Pay attention to
The subscript of mysql_fetch_row() returns the result array corresponding to the value on different attributes, and can only be obtained by subscript, not by attribute name, which is easy to cause confusion in practical application, 1 must be used carefully. At the same time, care should be taken not to use out-of-bounds subscripts in use.
The results of the example running correctly are as follows.

 Title:   The data structure 
 Price:  20
 Publication Date:  2001-01-01
 Title:  C language 
 Price:  23
 Publication Date:  1998-04-04
 Title:  PHP Introduction to technology 
 Price:  22
 Publication Date:  2005-05-01

Related articles: