Database Language Injection Configuration
Many applications written in PHP are connecting to a database. After connecting to the database from within the IDE, we can use language injections in PhpStorm to write our database-oriented code. The editor provides us full language support for SQL queries embedded in a string literal in PHP. We get syntax highlighting, code completion, navigation and inspections. And not only for our SQL statement, but also for any PHP variables we use in there.
PhpStorm does its best to recognize and parse SQL that contains other elements, but there are some cases where we have to help it a little bit. Some developers prefer to use sprintf() to format their queries. The IDE will not recognize the placeholders for column names, as we can see from the error:
Frameworks often have their own placeholders in queries. For example the Yii framework uses {{TableName}}
to refer to table names, replacing these placeholders with the correct database table name upon using it. Same thing here, though: the IDE is unable to recognize this placeholder by default:
How can we solve this? PhpStorm lets us customize SQL parameters! From the settings under Tools | Databases, we can tell PhpStorm which tokens the SQL analyzer should recognize as being valid. We’ll have to check Use in other language string literals, and then add a regular expression pattern.
The sprintf() tokens will be recognized by adding \%\w+
. For Yii’s placeholders, we could add \{\{\w+\}\}
. Not only will this remove the errors we saw earlier: adding custom SQL parameters will also make sure PhpStorm asks us for the placeholder value when running the query using Alt+Enter.
We would love to hear your feedback through the issue tracker, by posting in the comments below, or in our forums!
Develop with pleasure!
– JetBrains PhpStorm Team