how many ways we can retrieve the data in the result set of MySQL using PHP?

Last updated 3 years, 2 months ago | 3002 views 75     5

Tags:- PHP PHP-MySQL

PHP-MYSQL |  Fetch Recoards From MySql table

There are 4 ways:

  1. mysqli_fetch_row() - Get a result row as an enumerated array
  2. mysqli_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  3. mysqli_fetch_object() - Fetch a result row as an object
  4. mysqli_fetch_assoc() - Fetch a result row as an associative array
 

 


 

mysqli_fetch_row()

The mysqli_fetch_row() function return a result row as an enumerated array. 

Here is the example of mysqli_fetch_row() function.

<?php
// setup database
$con=mysqli_connect("localhost","user","password","db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();die();
  }

$sql="SELECT * FROM Persons WHERE id = 5";
$result=mysqli_query($con,$sql);

// fetch a single result set
$row=mysqli_fetch_row($result);

// print row data
print_r($row);


mysqli_close($con);
?>

 


 

mysqli_fetch_array()

The mysqli_fetch_array() function return the current row of result set as an associative array, a numeric array, or both.

Here is the example of mysqli_fetch_object() function.

<?php
// setup database
$con=mysqli_connect("localhost","user","password","db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();die();
  }

$sql="SELECT * FROM Persons";
$result=mysqli_query($con,$sql);

// fetch data as an associative array, a numeric array, or both
$row=mysqli_fetch_array($result);

// print row data
print_r($row);


mysqli_close($con);
?>

 


 

mysqli_fetch_object()

The mysqli_fetch_object() function returns the current row of a result set, as an object.

Here is the example of mysqli_fetch_object() function.

<?php
// setup database
$con=mysqli_connect("localhost","user","password","db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();die();
  }

$sql="SELECT * FROM Persons";
$result=mysqli_query($con,$sql);

// fetch data as an object
$row=mysqli_fetch_array($result);

// print row data
print_r($row);


mysqli_close($con);
?>

 


 

mysqli_fetch_assoc()

The mysqli_fetch_assoc() function return the current row of result set as an associative array.

Here is an example of mysqli_fetch_assoc() function.
 

<?php
// setup database
$con=mysqli_connect("localhost","user","password","db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();die();
  }

$sql="SELECT * FROM Persons";
$result=mysqli_query($con,$sql);

// fetch data as an associative array
$row=mysqli_fetch_assoc($result);

// print row data
print_r($row);


mysqli_close($con);
?>