← Back to Chapters

PHP CRUD Class – Select Method

? PHP CRUD Class – Select Method

? Quick Overview

The Select method in a PHP CRUD class is used to retrieve records from a database securely using prepared statements. It supports fetching single or multiple rows and returns data in an associative array format.

? Key Concepts

  • Prepared statements for security
  • Reusable CRUD class structure
  • Fetching multiple vs single records
  • Associative array results

? Syntax & Theory

The Select method uses mysqli::prepare(), binds parameters if required, executes the query, and fetches results using fetch_all() or fetch_assoc().

? CRUD Class with Select Method

? View Code Example
// PHP CRUD class with select methods
class User {
private $conn;
private $table = "users";

public function __construct($db) {
$this->conn = $db;
}

public function selectAll() {
$stmt = $this->conn->prepare("SELECT id, first_name, last_name, email FROM " . $this->table);
$stmt->execute();
$result = $stmt->get_result();
return $result->fetch_all(MYSQLI_ASSOC);
}

public function selectById($id) {
$stmt = $this->conn->prepare("SELECT id, first_name, last_name, email FROM " . $this->table . " WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
return $result->fetch_assoc();
}
}

? Using the Select Method

? View Code Example
// Using the select methods from the CRUD class
$conn = new mysqli("localhost","username","password","myDB");

$user = new User($conn);

$allUsers = $user->selectAll();
foreach ($allUsers as $u) {
echo $u['id']." - ".$u['first_name']." ".$u['last_name']." - ".$u['email']."<br>";
}

$singleUser = $user->selectById(1);
echo "Selected User: ".$singleUser['first_name']." ".$singleUser['last_name'];

$conn->close();

? Live Output / Explanation

The selectAll() method returns all user records, while selectById() fetches a single user based on ID.

?️ Interactive Example

You can display the fetched users dynamically in an HTML table or dashboard, making this method ideal for admin panels and reports.

? Use Cases

  • Displaying user lists
  • Fetching profile details
  • Admin dashboards
  • Data reporting tools

✅ Tips & Best Practices

  • Always validate IDs before querying
  • Use pagination for large datasets
  • Reuse select methods for filtering
  • Close connections after use

? Try It Yourself

  • Add selectByEmail() method
  • Implement pagination logic
  • Render users in an HTML table
  • Combine select with update/delete