« Back to History
ajax_table_options.php
|
20260721_154032.php
Initial Bulk Import
Copy Code
<?php /* ajax_table_options.php Returns JSON arrays of distinct values for columns grouped by company for a given whitelisted table. Usage (GET): ajax_table_options.php?tbl=yarn_out&company=The%20Company%20Name Module-local; respects company_id scope from auth. */ header('Content-Type: application/json; charset=utf-8'); error_reporting(0); /* Bootstrap minimal auth/db like yarn_entry_manage */ if (file_exists(__DIR__ . '/modules/auth/page_acl.php')) { require_once __DIR__ . '/modules/auth/page_acl.php'; $ctx = page_require_access('yarn_entry_manage'); $company_scope_id = (int)($ctx['company_id'] ?? 0); $pdo = $ctx['pdo'] ?? null; } else { require_once __DIR__ . '/modules/auth/auth.php'; require_login(); $u = auth_user(); $company_scope_id = (int)($u['company_id'] ?? 0); $pdo = $GLOBALS['pdo'] ?? null; } if (!$pdo) { require __DIR__ . '/core/db.php'; $pdo = $GLOBALS['pdo'] ?? null; } /* whitelist same as yarn_entry_manage */ $allowed_tables = [ 'yarn_in','yarn_out','tpm_in','tpm_out','tfo_in','tfo_out','zari_in','zari_out' ]; $tbl = $_GET['tbl'] ?? ''; $company = $_GET['company'] ?? ''; if (!in_array($tbl, $allowed_tables)) { echo json_encode(['error'=>'invalid_table']); exit; } $company = trim((string)$company); if ($company === '') { echo json_encode(['error'=>'missing_company']); exit; } try { $params = [':company' => $company]; $where = " WHERE company = :company "; if ($company_scope_id > 0) { $where .= " AND company_id = :cid "; $params[':cid'] = $company_scope_id; } $cols_to_fetch = ['yarn_type','denier','color','assign_to']; $out = []; // fetch table structure once $stmt = $pdo->prepare("DESCRIBE `$tbl`"); $stmt->execute(); $fields = array_column($stmt->fetchAll(PDO::FETCH_ASSOC),'Field'); foreach ($cols_to_fetch as $col) { if (!in_array($col, $fields)) { $out[$col] = []; continue; } $sql = "SELECT DISTINCT `$col` AS v FROM `$tbl` $where AND `$col` IS NOT NULL AND `$col` != '' ORDER BY `$col`"; $st = $pdo->prepare($sql); $st->execute($params); $vals = array_map(function($r){ return $r['v']; }, $st->fetchAll(PDO::FETCH_ASSOC)); $out[$col] = $vals; } echo json_encode(['ok'=>1,'data'=>$out], JSON_UNESCAPED_UNICODE); } catch (Exception $e) { echo json_encode(['error'=>'server_error']); }