How to execute plain SQL in typo3 version 10 ($GLOBALS['TYPO3_DB']->sql_query())?

Viewed 1180

Is there a way to execute plain SQL in typo3 version 10? How can I do this?

// in previous versions you could do the following
$sql = 'SELECT * FROM tt_content;';
$GLOBALS['TYPO3_DB']->sql_query($sql);
while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
  // ...
}

EDIT

The simple script SELECT * FROM tt_content is only a placeholder. I want do some special migrations or some special requests for my statistic page.

3 Answers
$connection = GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionForTable('tt_content');
$resultSet = $connection->query('SELECT * FROM tt_content')->execute();

Works with TYPO3 9 for me.

    // looky-looky at 20200609: https://www.strangebuzz.com/en/snippets/running-raw-sql-queries-with-doctrine
    /** @var Connection $connection */
    $connection = GeneralUtility::makeInstance(ConnectionPool::class)
        ->getConnectionForTable(self::TABLENAME);
    /** @var DriverStatement $statement */
    $statement = $connection->prepare($sql);
    $statement->execute();

Thanks to Idea

There is no need to execute raw SQL in TYPO3 anymore since the Doctrine-based DBAL API is powerful and allows you to do basically anything.

Your example using the TYPO3 Connection class:

$result = GeneralUtility::makeInstance(ConnectionPool::class)
    ->getConnectionForTable('tt_content')
    ->select(['*'], 'tt_content');

foreach ($result as $row) {
    // ...
}

Related