Using vanilla PHP without a framework means you'll need to handle database connections and queries manually. Here’s how you can implement the filtering in a vanilla PHP setup:
Step 1: Database Connection
First, ensure you have a database connection.
// db.php
$host = 'your_host';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
Step 2: Fetch User-Specific Projects
Create a function to get the projects for the user.
// functions.php
function getProjectsForUser($pdo, $userId) {
$stmt = $pdo->prepare("SELECT project_id FROM projects_companies WHERE company_id = :company_id");
$stmt->execute(['company_id' => $userId]);
return $stmt->fetchAll(PDO::FETCH_COLUMN); // Returns an array of project IDs
}
Step 3: Filter Contractors Based on Projects
Create a function to get contractors for the projects.
function getContractorsForProjects($pdo, $projectIds) {
$placeholders = str_repeat('?,', count($projectIds) - 1) . '?';
$stmt = $pdo->prepare("SELECT contractor_id FROM contractors_projects WHERE project_id IN ($placeholders)");
$stmt->execute($projectIds);
return $stmt->fetchAll(PDO::FETCH_COLUMN); // Returns an array of contractor IDs
}
Step 4: Apply the Filter in Grocery Crud
Use the filtered contractor IDs to set the where clause in Grocery Crud.
require 'db.php';
require 'functions.php';
// Assuming you have a way to get the current user's ID
$userId = 1; // Replace with actual user ID retrieval logic
$projects = getProjectsForUser($pdo, $userId);
$projectIds = $projects; // Already an array of project IDs
$contractors = getContractorsForProjects($pdo, $projectIds);
$contractorIds = $contractors; // Already an array of contractor IDs
// Include Grocery Crud
require_once 'path/to/grocery_crud.php';
$crud = new grocery_CRUD();
$crud->set_table('contractors')
->set_relation('contractor_id', 'contractors', '{contractor_name}') // Adjust based on your actual column names
->where_in('contractor_id', $contractorIds) // Apply the filter
->columns(['contractor_id', 'other_columns']); // Add other columns as needed
$output = $crud->render();
// Output the Grocery Crud interface
include 'output_template.php'; // Create a template to output the Grocery Crud render
Explanation
- Database Connection: The
db.php file sets up a PDO connection to the database.