Files
gravity/Dashboard ลดแออัด-ลดรอคอย/.agents/rules/php_pdo_best_practices.md
T
2026-09-16 23:20:08 +07:00

1.5 KiB

PHP PDO and Data Fetching Best Practices

When fetching data from SQL databases (like MySQL/MariaDB) and displaying it on the frontend, always adhere to the following rules to prevent silent failures and ensure robust data pipelines:

  1. Case-Insensitive PDO Parameter Binding: When dynamically injecting parameters like :start and :end into a user-defined SQL string, always use regex (e.g., preg_match_all) to extract the exact case of the parameter name used in the SQL. Do not hardcode $params['start'] if checking case-insensitively, because PDO named parameters are strictly case-sensitive. If the SQL has :START, binding ['start' => ...] will throw an Invalid parameter number exception.

  2. Case-Insensitive Column Aliases: SQL engines may return column names in uppercase (e.g. CAUSE) depending on the driver or the exact text in the query. Always use array_change_key_case($row, CASE_LOWER) after $stmt->fetch(\PDO::FETCH_ASSOC) to normalize keys to lowercase before accessing them in PHP.

  3. Isolated Try-Catch Blocks for Multiple Queries: When a single PHP endpoint or block processes multiple independent SQL queries (e.g., rendering multiple dashboard charts), never wrap them all in a single try-catch block. Wrap EACH query in its own try-catch block. This ensures that if one query fails (e.g., due to a syntax error or a missing column), it does not abort the execution of the subsequent, perfectly valid queries.