How can we fetch all the data from MySQL table by using mysql_fetch_array() function, returning an array with the numeric index, in PHP script?

The function mysql_fetch_array() returns an array with numeric indexes when you use the constant MYSQL_NUM as the second argument. This allows you to access fetched data using numeric indexes like $row[0], $row[1], etc.

Syntax

mysql_fetch_array($result, MYSQL_NUM)

Parameters

  • $result − The result resource returned by mysql_query()
  • MYSQL_NUM − Constant that specifies numeric index array

Example

In this example, we fetch all records from a table named 'tutorials_tbl' using mysql_fetch_array() with MYSQL_NUM to get numeric indexes −

<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);
   
   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
   
   $sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl';
   mysql_select_db('TUTORIALS');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }

   while($row = mysql_fetch_array($retval, MYSQL_NUM)) {
      echo "Tutorial ID :{$row[0]} <br> ".
           "Title: {$row[1]} <br> ".
           "Author: {$row[2]} <br> ".
           "Submission Date : {$row[3]} <br> ".
           "--------------------------------<br>";
   }
   echo "Fetched data successfully<br>";
   mysql_close($conn);
?>

Output

Tutorial ID :1 
Title: Learn PHP 
Author: John Doe 
Submission Date : 2023-01-15 
--------------------------------
Tutorial ID :2 
Title: MySQL Basics 
Author: Jane Smith 
Submission Date : 2023-01-20 
--------------------------------
Fetched data successfully

Key Points

  • Access data using numeric indexes: $row[0], $row[1], etc.
  • Index order matches the column order in your SELECT statement
  • Use MYSQL_ASSOC for associative arrays or MYSQL_BOTH for both types

Conclusion

The mysql_fetch_array() function with MYSQL_NUM provides an efficient way to access database results using numeric indexes. Note that mysql_* functions are deprecated; use MySQLi or PDO for new projects.

Updated on: 2026-03-15T07:23:54+05:30

800 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements