How can we display all the records from MySQL table with the help of PHP script?

To illustrate this we are fetching all the records from a table named ‘Tutorials_tbl’ with the help of PHP script that uses mysql_query() and mysql_fetch_array() function in the following example −

   $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';

   $retval = mysql_query( $sql, $conn );

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

   while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
      echo "Tutorial ID :{$row['tutorial_id']} <br> ".
         "Title: {$row['tutorial_title']} <br> ".
         "Author: {$row['tutorial_author']} <br> ".
         "Submission Date : {$row['submission_date']} <br> ".
   echo "Fetched data successfully
";    mysql_close($conn); ?>

In the above example, the constant MYSQL_ASSOC is used as the second argument to the PHP function mysql_fetch_array(), so that it returns the row as an associative array. With an associative array, you can access the field by using their name instead of using the index.

Updated on: 22-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started