PHP mysqli_fetch_assoc() Tutorial 🎯

beginner
19 min

PHP mysqli_fetch_assoc() Tutorial 🎯

Welcome to our comprehensive guide on using mysqli_fetch_assoc() in PHP! In this lesson, we'll delve into this powerful function, explain its purpose, and show you how to use it effectively in your projects.

What is mysqli_fetch_assoc()? πŸ“

mysqli_fetch_assoc() is a function in PHP that helps you fetch data as an associative array from a result set returned by a MySQLi database query. It's an essential tool for working with databases in PHP.

Why use mysqli_fetch_assoc()? πŸ’‘

Using mysqli_fetch_assoc() is beneficial because it allows you to easily access data using column names as array keys. This makes your code more readable and easier to manage, especially when dealing with large datasets.

How to use mysqli_fetch_assoc() πŸ“

To use mysqli_fetch_assoc(), you'll first need to establish a connection with your MySQL database, execute a query, and then fetch the results. Here's a step-by-step breakdown:

  1. Establish a database connection:
php
$db = new mysqli("localhost", "username", "password", "database");
  1. Execute a query:
php
$result = $db->query("SELECT * FROM table_name");
  1. Fetch the data using mysqli_fetch_assoc():
php
while ($row = $result->fetch_assoc()) { echo $row["column_name"]; }

Advanced Example 🎯

Let's create a simple example where we fetch data from a user table:

php
<?php $db = new mysqli("localhost", "username", "password", "database"); $result = $db->query("SELECT * FROM users"); while ($user = $result->fetch_assoc()) { echo "User ID: " . $user["id"] . ", Name: " . $user["name"] . ", Email: " . $user["email"] . "\n"; } ?>

πŸ’‘ Pro Tip: Remember to check if the connection is successful before executing any queries. You can use the connect_error function for this purpose.

Quiz 🎯

:::quiz Question: What function in PHP helps you fetch data as an associative array from a result set? A: mysqli_fetch_array() B: mysqli_fetch_assoc() C: mysqli_fetch_obj() Correct: B Explanation: mysqli_fetch_assoc() fetches data as an associative array, which allows you to access data using column names as array keys.