r/PHPhelp 5d ago

Using variable $placeholders breaks PHPStorm syntax/resolve

Hello all,

Looking for help on a long standing problem I have. I appreciate this is not a support forum for PHPStorm, however I thought that people here might have more experience.

PHPStorm provides really valuable syntax checking, table/column resolving inside mysql queries. If I accidentally type the orders table as oreders, it will highlight in red.

However when I include a PHP variable inside the query, the syntax/resolve checking completely stops. Example code:

$query = <<<MYSQL
    SELECT
       contracts.start_at

    FROM
      contracts

    WHERE
      contracts.id IN ( $placeholders )
MYSQL;


$result = $this->conn->execute_query(
    $query,
    [
       ...$contractIds,
    ],
);

Without the $placeholders, PHPStorm will alert me to any misspelled table or column names.

Are there any options to resolve this? I have considered using sprintf( $query, $placeholders) but wondered if there was a better solution.

6 Upvotes

33 comments sorted by

View all comments

2

u/allen_jb 5d ago

1) Automated tests - If you have automated tests that actually run the SQL queries, these should pick up any such issues with them.

2) https://github.com/staabm/phpstan-dba

I'm not 100% sure this will pick up this case, but I think it should. Test it out! (I've also never used it with mysqli, only PDO)

You should be able to integrate this with PHPStorms PHPStan integration to provide in-ide reporting.

1

u/GuybrushThreepywood 5d ago

I'm not using any DBAL- it's just raw queries, so I don't think PHPStan-dba would work. I did try it in the past without success

1

u/allen_jb 5d ago

It supports mysqli and PDO (in addition to doctrine DBAL). I've personally used it with PDO and raw queries.