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.
The Select method uses mysqli::prepare(), binds parameters if required, executes the query, and fetches results using fetch_all() or fetch_assoc().
// 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 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();
The selectAll() method returns all user records, while selectById() fetches a single user based on ID.
You can display the fetched users dynamically in an HTML table or dashboard, making this method ideal for admin panels and reports.