0

I'm trying to display sql query on page in drupal 8.2, but I get an error:

The controller must return a response (Object(Drupal\Core\Render\Markup) given).

How should I change the following code?

if ($result = $mysqli->query("SELECT id, discipline, teacher FROM canteach")) {
  $output .= "Select вернул " . $result->num_rows . " строк <br />";
}

$mysqli->close();

$header = array('id', 'Discipline', 'Teacher');
$rows = array();

while ($row = $result->fetch_array(MYSQLI_NUM)) {
  $rows[] = array($row->id, $row->discipline, $row->teacher);
}

$result->close();

$items_array = array(
  '#theme' => 'table',
  '#items' => array('header' => $header, 'rows' => $rows),
);

return render($items_array);
1
  • Welcome to Drupal Answers! It seems you are mixing up Drupal 8 code with Drupal 7 code, and plain PHP code. Drupal 8 code doesn't use fetch_array() or MYSQLI_NUM (nor does Drupal 7). Plus, you are not even showing the rest of the code, so we cannot know which method is using the code you are showing.
    – avpaderno
    Commented May 4, 2016 at 21:25

1 Answer 1

2

From the error, I assume your code is in a controller? In that case, take note that you should return a render array or an object inheriting the Response class, not HTML.

In your case, just do:

return $items_array;

instead of

return render($items_array);

But wait!

The table render array should be constructed this way:

$items_array = array(
  '#theme' => 'table',
  '#header' => $header, 
  '#rows' => $rows,
); 

For a reference of what you can pass in, check out https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21table.html.twig/8.1.x

Other notes

The way you are querying data is not wrong per se but definitely not the "Drupal way". To perform queries using Drupal's DBAL, check out https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!database.api.php/group/database/8.2.x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.