Current Location: Home> Function Categories> mysql_fetch_array

mysql_fetch_array

Get a row from the result set as an associative array, or an array of numbers, or both.
Name:mysql_fetch_array
Category:Uncategorized
Programming Language:php
One-line Description:Get a row from the result set as an associative array or array of numbers and move the pointer backward

Function name: mysql_fetch_array()

Applicable version: PHP 4, PHP 5, PHP 7

Usage: The mysql_fetch_array() function takes a row from the result set as an associative array or array of numbers and moves the pointer backward.

grammar:

 mixed mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )

parameter:

  • $result: Required, representing the resource identifier of the result set.
  • $result_type: optional, indicating the type of the returned array. It can be MYSQL_ASSOC, MYSQL_NUM or MYSQL_BOTH, and the default is MYSQL_BOTH.

Return value:

  • If successful, a associative array or numeric array is returned, containing a row of data obtained from the result set. If there are no more rows, false is returned.

Example:

Suppose we have a database table named "users" with the fields "id", "name" and "email".

Connect to the database and execute SQL queries:

 $conn = mysql_connect("localhost", "username", "password"); mysql_select_db("database_name", $conn); $result = mysql_query("SELECT * FROM users", $conn);

Use the mysql_fetch_array() function to get a row of data in the result set and return it as an associative array:

 $row = mysql_fetch_array($result, MYSQL_ASSOC);

Now we can access each field in the associative array:

 echo "ID: " . $row["id"] . "<br>"; echo "Name: " . $row["name"] . "<br>"; echo "Email: " . $row["email"] . "<br>";

If you need to return a row of data in the result set as an array of numbers, you can set the $result_type parameter to MYSQL_NUM:

 $row = mysql_fetch_array($result, MYSQL_NUM);

Now we can access each field through the index:

 echo "ID: " . $row[0] . "<br>"; echo "Name: " . $row[1] . "<br>"; echo "Email: " . $row[2] . "<br>";

Note that when using the mysql_fetch_array() function, you can choose not to pass the $result_type parameter. By default, a merged array (MYSQL_BOTH) containing an associative array and a numeric array is returned. According to the specific requirements, select the appropriate parameter type to obtain the data. In addition, it is recommended to use mysqli or PDO extensions instead of mysql functions, because the mysql function has been removed in PHP 7.

Similar Functions
Popular Articles