Return a PDO query in an array

Asked

Viewed 7,439 times

3

How do I perform a query with PDO and return the results in a array.

Ex: I need to make a query that returns me 10 rows, each row has 3 columns

<?php

$equipe1 = $_POST['equipe1'];//Pega o Nome da equipe
$equipe2 = $_POST ['equipe2'];//Pega o Nome da equipe
$dificuldade = $_POST ['dificuldade'];//Define a dificuldade das perguntas      que seram selecionadas
$rodada = $_POST ['rodada'];//Número de perguntas que serão retornadas

echo $equipe1;
echo $equipe2;

switch ($dificuldade) {
  case '1':
   $dificuldade = "Facil";
  break;

  case '2':
   $dificuldade = "Medio";
  break;

  case '3':
   $dificuldade = "Dificil";
  break;
}

switch ($rodada) {
  case '1':
    $rodada = "10";
  break;
  case '2':
    $rodada = "15";
  break;
  case '3':
    $rodada = "20";
  break;

try{
 $conexao = new PDO ("mysql:host=localhost; dbname=teocratico; charset=utf8","root","");
 } catch (PDOException $erro){
   echo $erro->getmessage();
   //header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
 }


$consulta = $conexao -> query ("SELECT id_pergunta, pergunta, resposta, desafio FROM perguntas 
where dificuldade ='$dificuldade' LIMIT $rodada ORDER BY RAND()

");
// Vamos imprimir os nossos resultados
  while($row = $consulta->fetch()) {
      echo $row['id_pergunta']. ' - '. $row['pergunta'] . ' - ' .    $row['resposta'] . ''. $row ['desafio'];
  }
}


?>
  • I did not understand very well what you want.. What you want different from what you are now?

  • What’s the problem with the code?

1 answer

4


I’m not sure if it’s duplicate...

You can do the following:

// Cria conexão com o banco de dados
$db = new PDO("mysql:host=".dbhost.";dbname=".dbschema.";charset=utf8;", dbuser, dbpassword);
// Seta atributos para gerar erros caso ocorra alguma exceção
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Faz a consulta
$sql = "Sua consulta SQL";
$query = $db->query($sql);
// O segredo esta nesta linha abaixo \/
$return = $query->fetch();

There are 4 directives from fetch that personally I find interesting to use in a consultation:

$query->fetch(); // It returns only one element of the query, I believe the first... If the query has more than one element, the others are ignored

$query->fetchAll(); // Returns all elements of the query

And you can still pass as parameter:

$query->fetchAll(PDO::FETCH_ASSOC); // Returns an element of the type array, which can be accessed like this: $query["element"]

$query->fetchAll(PDO::FETCH_OBJ); // Returns an element of the type object, which can be accessed like this: $query->element

There are still many other directives that can be accessed here


So if you have for example the following table:

─────────────────────────────────────────────────────────
|   Nome        |   Email                   |   Sexo    |
─────────────────────────────────────────────────────────
|   Joaozinho   |   [email protected]          |   H       |
─────────────────────────────────────────────────────────
|   Mariazinha  |   [email protected]       |   M       |
─────────────────────────────────────────────────────────
|   Carlinhos   |   [email protected]    |   H       |
─────────────────────────────────────────────────────────

To achieve the goal of displaying all the elements you could do:

$return = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($return as &$value) {
    echo "Nome: ".$value['nome']." Email: ".$value['email']." Sexo: ".$value['sexo'];
}
  • Query does not run, I tested it directly in the database and it worked.

  • while($Row = $query->fetchAll(PDO::FETCH_ASSOC)) { echo $Row['id_question']. ' - '. $Row['question'] . ' - ' . $Row['answer'] . '. $Row ['challenge']; }

  • But when I do in PHP it doesn’t work. it from Undefined index: in array.

  • Note that the mode you are running is different from my answer rs in which array it from Undefined index?

Browser other questions tagged

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