r/PHPhelp • • Sep 05 '26

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.

8 Upvotes

38 comments sorted by

View all comments

Show parent comment

1

u/GuybrushThreepywood Oct 22 '26

Could you show an example of how you're using it?

1

u/colshrapnel Oct 22 '26

Well, it's purely manual approach, no library was made. Also, I am using it mainly for the conditional query parts.

$sql = "SELECT * FROM table 
        WHERE foo=? AND bar=? AND baz=? AND OCTET_LENGTH(1) 
        ORDER BY OCTET_LENGTH(2)";
$data = [$foo, $bar, $baz];

$where = '';
if ($from && $to) {
    $data[] = $from;
    $data[] = $to;
    $where = "AND date BETWEEN ? AND ?";
}
$order_by = Foo::ORDER_COLUMNS[$order] ?? Foo::ORDER_COLUMNS[Foo::DEFAULT_ORDER_COLUMN];
$order_by .= " " . (in_array($dir, ['asc','desc'], true) ? $dir : Foo::DEFAULT_ORDER_DIR);
$replace = [
    'AND OCTET_LENGTH(1)' => $where ?: '',
    'OCTET_LENGTH(2)' => $order_by,
];
$sql = strtr($sql, $replace);
$rows = DB::all($sql, $data);

Disclaimer: it's a made up sketch code, there could be errors in it.

It looks a bit clumsy but in the end it produces clean SQL and safe database interaction. While keeping PHPstorm database inspection in place