If you want to use queries I wouldn't use pure SQL as you can't always sanitize your values that way and there's a risk of SQL injection. Instead, you can use Magento objects to make them.
- In a constructor of your model class inject
Magento\Framework\App\ResourceConnection
public function __construct( Magento\Framework\App\ResourceConnection $resource )
- Get the connection object
$this->conn = $resource->getConnection();
- Make an
insert query
$table_name = $this->conn->getTableName("custom_table"); $new_data = [ "key" => "my_custom_field", "value" => $custom_field_value ]; $this->conn->insert($table_name, $new_data);
*) You can also write an update query that way
$table_name = $this->conn->getTableName("custom_table"); $new_data = [ "key" => "my_custom_field", "value" => $custom_field_value ]; $where = ["entity_id = ?" => $entity_id]; $this->conn->update($table_name, $new_data, $where);
*) Or select query:
$sql = "SELECT * FROM `some_table` WHERE `name_col` = :name"; $bind = [ ":name" => $name ]; $result = $this->conn->query($sql, $bind);