How to create Array with BD content

Asked

Viewed 111 times

0

I’m trying to create an array with the contents of a tabela of my banco but somehow, I tried to do this:

// ATRIBUI UMA CONEXÃO PDO   
$pdo = Conexao::getInstance();
// ATRIBUI UMA INSTÂNCIA DA CLASSE CRUD
$crud = Crud::getInstance($pdo, 'cadAgendaEvento');

// BUSCANDO EVENTOS
$sqlEvento = "SELECT * FROM `cadAgendaEvento`";

$dados = array();

foreach ($sqlEvento as $Retorno) {                      

    $dados = $Retorno;  

    echo json_encode(
        array(
            "success" => 1,
            "result" => $dados
        )
    );                              
}

I wonder if this format is correct, apparently not returning me anything.

1 answer

0


By resemblance to code, I assume you’re using this library: http://www.devwilliam.com.br/php/crud-generico-com-php-e-pdo

If applicable, just use the method:

public function getSQLGeneric($sql, $arrayParams=null, $fetchAll=TRUE)`

For example:

// BUSCANDO EVENTOS
$dados = $crud->getSQLGeneric($sqlEventos);

At that point the variable $dados will already be an array with the database data.

You can browse this data using a foreach:

foreach ($dados as $dado) {   
    echo $dado;               
}

If you want to print a json the way it showed in your code, you don’t need the for:

echo json_encode(array(
        "success" => 1,
        "result" => $dados
));
  • Hello @Pantera, thanks for the tip, I’m really using the mentioned library, but tell me one thing, this last example takes all the database records and assembles this array?

  • @adventistapr, yes. As the third method parameter getSQLGeneric, when omitted, contains the value TRUE, the variable $dados will always be an array with all records your query. The documentation of the fetchAll PHP has more details on how this works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.