2

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.

koalabruder
  • 2,794
  • 9
  • 33
  • 40

3 Answers3

5
$connection = GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionForTable('tt_content');
$resultSet = $connection->query('SELECT * FROM tt_content')->execute();
User366
  • 765
  • 4
  • 9
  • 2
    This may be a correct answer, but it’d be useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who may not be familiar with the syntax. Further, it can help reduce the need for follow-up questions. Would you mind updating your comment with additional details? – Jeremy Caney May 12 '20 at 04:18
  • The answer helped me, but of course it would have been nicer with an explanation. – koalabruder May 29 '20 at 14:10
  • I am not sure what kind of explanation can be because the code is trivial... Let me try to explain it: "You need to create a new instance of connection pool, get a database connection object from it and call its query() method". I hope it helps. – User366 May 30 '20 at 15:03
0

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

padina
  • 77
  • 5
-1

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) {
    // ...
}

Mathias Brodala
  • 5,905
  • 13
  • 30