Detail the method using mysql_fetch_array of to get the current row data

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

Like mysql_fetch_row(), the function mysql_fetch_array() takes the current row in the result set and automatically slides to the next row after the call. The definition is as follows.

array mysql_fetch_array(int result, int [result_type])

The parameters are described below.
(1) result: The result identifier returned by the function mysql_query() or mysql_db_query() to specify the type of SQL statement for the data to be fetched.
(2) result_type: Used to specify the result set type, optionally, PHP constant set {MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH}.
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. You can also use the property name to get the value on that property.
Failure: false.
The following example USES mysql_fetch_array() to obtain the book information in the Computers data table with a price not less than 20.

1    <!---- use mysql_fetch_array() To obtain data: mysql_fetch_array.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       //mysql_fetch_array() Get the data and output it 
12       while($row=mysql_fetch_array($result))
13       {
14            echo " Title:     ".$row[1]."<br>";
15            echo " Price:     ".$row["price"]."<br>";
16            echo " Publication Date:     ".$row["publish_date"]."<br>";
17            echo "<br>";
18       }
19   ?>

The example gets the current row data on line 12 using mysql_fetch_array(), and then gets the value of a property on the row 1 using the property index and the property name in the loop on lines 12 to 18. It is easy to see that the difference between mysql_fetch_array() and mysql_fetch_row() is that the former returns two copies of the result set held in the array, one of which can be accessed by the property index and the other by the property name.
Pay attention to
When accessing a value on an attribute by its name, if several attributes have the same name, the latter attribute of the index overrides the former. Therefore, when using attribute names to obtain data, avoid querying the attribute duplicate names in the result set.
The results of the sample run 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: