mysqli_fetch_assoc() and mysqli_fetch_array() both are used to print result data of SQL query in PHP. Mysqli_fetch_assoc vs Mysqli_fetch_array has just a single difference in accessing resultant data.
Index
Difference between mysqli_fetch_assoc() and mysqli_fetch_array()
The major difference between mysqli_fetch_assoc and mysqli_fetch_array is the output format of result data.
mysqli_fetch_assoc returns data in an associative array and mysqli_fetch_array returns data in a numeric array and/or in an associative array.
Mysqli_fetch_assoc()
mysqli_fetch_assoc returns data in an associative array with a column name as a key of the resultant array. Β Which means we can access the output array with a column name as a key of an array.
Example
<?php // mysql connection variable $conn = mysqli_connect("localhost","user_name","password","database_name") or die("Mysqli Connection Error"); // mysql query string $sql_query="SELECT * FROM employees"; // mysql output variable $result=mysqli_query($conn,$sql_query); // fetch data as an associative array $row=mysqli_fetch_assoc($result); // print row data echo $row["id"]." ".$row["name"]; mysqli_close($conn); ?>
Mysqli_fetch_array()
mysqli_fetch_array returns data in a numeric and an associative array, so we can access result data with a column name or an index value.
Example
<?php // mysql connection variable $conn = mysqli_connect("localhost","user_name","password","database_name") or die("Mysqli Connection Error"); // mysql query string $sql_query="SELECT * FROM clg"; // mysql output variable $result=mysqli_query($conn,$sql_query); // fetch data as an associative and a numeric array $row=mysqli_fetch_array($result); // print row data with key echo $row["id"]." ".$row["name"]; // print row data with index echo $row[0]." ".$row[1]; mysqli_close($conn); ?>
Read Also: MySQL Interview Questions and Answers
Conclusion
Now we finally know the main difference between mysqli_fetch_array and mysqli_fetch_assoc. We can use both methods to access output data according to our requirements.
Enjoy Programming π