How to Write Select Query in Magento 2 with Standard way?

You can write a select query in Magento 2 to retrieve records from the table. The select query can be written with best practice to avoid security breaches.

Example, You are searching for records from the core_config_data table,
Row query is:

SELECT * FROM core_config_data WHERE scope = ‘default’ AND path = ‘general/locale/code’

You can direct use above string as query and pass it to the query() method but it’s not a secure way to write a select query. I will show you the standard Magento way to write database queries with the best secure standard Practice.

Above Query [‘*’] indicates fetch all the field of the table. You can pass a specific field by comma-separated also if you want.

You need to pass each where conditions as separately in the query with bind parameter.

Pass $path and $scope Value to the bind array instead of directly passing the value to the given where conditions.

  • An alternative of bind (Second Way)
    If you don’t want to use $bind you can use an alternative way to pass the parameter in where conditions by the given way,

Output