diff --git a/system/Database/MySQLi/PreparedQuery.php b/system/Database/MySQLi/PreparedQuery.php index e9a6c6d10e30..21ab29bc9441 100644 --- a/system/Database/MySQLi/PreparedQuery.php +++ b/system/Database/MySQLi/PreparedQuery.php @@ -75,6 +75,8 @@ public function _execute(array $data): bool $bindTypes .= 'i'; } elseif (is_numeric($item)) { $bindTypes .= 'd'; + } elseif (is_string($item) && mb_detect_encoding($item, 'UTF-8', true) === false) { + $bindTypes .= 'b'; } else { $bindTypes .= 's'; } diff --git a/system/Database/SQLite3/PreparedQuery.php b/system/Database/SQLite3/PreparedQuery.php index 21dc4c2fdeff..b86bd9981f49 100644 --- a/system/Database/SQLite3/PreparedQuery.php +++ b/system/Database/SQLite3/PreparedQuery.php @@ -75,6 +75,8 @@ public function _execute(array $data): bool $bindType = SQLITE3_INTEGER; } elseif (is_float($item)) { $bindType = SQLITE3_FLOAT; + } elseif (is_string($item) && mb_detect_encoding($item, 'UTF-8', true) === false) { + $bindType = SQLITE3_BLOB; } else { $bindType = SQLITE3_TEXT; } diff --git a/tests/system/Database/Live/PreparedQueryTest.php b/tests/system/Database/Live/PreparedQueryTest.php index fd3b6cedb403..83eb143f1b18 100644 --- a/tests/system/Database/Live/PreparedQueryTest.php +++ b/tests/system/Database/Live/PreparedQueryTest.php @@ -269,4 +269,23 @@ public function testDeallocatePreparedQueryThenTryToClose(): void $this->query->close(); } + + public function testInsertBinaryData() + { + if ($this->db->DBDriver === 'Postgre' || $this->db->DBDriver === 'SQLSRV') { + $this->markTestSkipped('Blob not supported for Postgre and SQLSRV.'); + } + + $this->query = $this->db->prepare(static fn ($db) => $db->table('type_test')->insert([ + 'type_blob' => 'blob', + ])); + + $fileContent = file_get_contents(TESTPATH . '_support/Images/Steveston_dusk.JPG'); + $this->assertTrue($this->query->execute($fileContent)); + + $id = $this->db->insertId(); + $file = $this->db->table('type_test')->where('id', $id)->get()->getRow(); + + $this->assertSame(strlen($fileContent), strlen($file->type_blob)); + } } diff --git a/user_guide_src/source/changelogs/v4.5.6.rst b/user_guide_src/source/changelogs/v4.5.6.rst index 569c5a542ecd..2b812ef232e7 100644 --- a/user_guide_src/source/changelogs/v4.5.6.rst +++ b/user_guide_src/source/changelogs/v4.5.6.rst @@ -42,6 +42,7 @@ Bugs Fixed - **CURLRequest:** Added support for handling proxy responses using HTTP versions other than 1.1. - **Database:** Fixed a bug that caused ``Postgre\Connection::reconnect()`` method to throw an error when the connection had not yet been established. - **Model** Fixed a bug that caused the ``Model::getIdValue()`` method to not correctly recognize the primary key in the ``Entity`` object if a data mapping for the primary key was used. +- **Database:** Fixed a bug with handling binary data with prepared statements in SQLite3 and MySQLi drivers. See the repo's `CHANGELOG.md `_