0

Could you help help me correct the follow piece of code

I am getting the following error.

"The website encountered an unexpected error. Please try again later."

public function __construct(Connection $connection) {
    $this->connection = Database::getConnection();
  }
public function hello($state = '0') {
    $sqlQuery = $connection->select('pop11', 'C2011')
    ->fields('C2011', array('male', 'female'))
    ->condition('C2011.sCode', '10', '=');
    $data = $sqlQuery->execute();        
    if ($data) {
        $results = $data->fetchAll(\PDO::FETCH_OBJ);
        foreach ($results as $row) {
        echo "Field a: {$row->male}, field b: {$row->female}";
        }            
    }else{
        return array('#title' => 'Error', '#markup' => 'Could not Find. What you are Looking for.',);
    }

}
1

$connection doesn't exist in the context of hello(). You need to use $this->connection if you're wanting to use the Connection that's built in your object.

  • 1
    Also you are injecting a Connection object into the constructor but then creating another one statically, which frankly does not make sense. – cilefen Aug 3 '16 at 20:51
0

Finally I have the solution after trying a lot of example code from different websites...

namespace Drupal\hello_world\Controller;

use Drupal\Core\Database\Connection;

class HelloWorldController {

public function hello($state = '0') {


   $sqlResult = db_select('pop11', 'C2011')
    ->fields('C2011', array('male', 'female'))
    ->condition('C2011.code', '10', '=')->execute() ->fetchAll();

    foreach ($sqlResult as $row) {
        echo "Field a: {$row->male}, field b: {$row->female}";
    }   

}

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.