← Back to Chapters

PHP MySQL CRUD – Read Data

? PHP MySQL CRUD – Read Data

? Quick Overview

The Read operation is the second step in CRUD (Create, Read, Update, Delete). It retrieves data from a MySQL database and displays it using PHP with SELECT queries and extensions like MySQLi or PDO.

? Key Concepts

  • Reads existing records
  • Uses SQL SELECT queries
  • Fetches data row by row
  • Outputs results dynamically

? Syntax / Theory

  • MySQLi establishes database connections
  • query() executes SQL
  • fetch_assoc() returns associative arrays
  • Loops display multiple rows

? Code Example

? View Code Example
// Read user records from MySQL database
<?php
$conn = new mysqli("localhost","username","password","myDB");

if ($conn->connect_error) {
die("Connection failed");
}

$sql = "SELECT id, first_name, last_name, email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["first_name"]." ".$row["last_name"]."<br>";
}
}

$conn->close();
?>

? Live Output / Explanation

  • Connects to database
  • Executes SELECT query
  • Displays each record
  • Closes connection

? Use Cases

  • Admin dashboards
  • User management systems
  • Product listings
  • Reports & analytics

✅ Tips & Best Practices

  • Use prepared statements
  • Paginate large data
  • Validate connections

? Try It Yourself

  • Display data in table format
  • Add search filter
  • Implement pagination