Doubt with foreach

Asked

Viewed 176 times

-1

This system is done using PDO library , mvc and bootstrap, I will explain my question.

In the controller part I have a file QuestãoController.php there I created a method chamaFormulário(), within this method I instate his DAO file QuestaoDAO there are all select to fetch a data in the bank I need to do a foreach to get certain field of the table of my bank in the case table questoes

Questoesdao.php

<?php
require_once ("../library/data/DataBase.php");

class QuestoesDAO extends DataBase {

 private $tabela = "questoes";

 // Retorna todos os dados da tabela questoes
 public function getAll()
 {
    return $this->db->select("SELECT * FROM {$this->tabela}");
 }

 // Retorna uma questão em particular
 public function getById($id)
 {
    $id = (int)$id;
    return $this->db->select("SELECT QUESTOES FROM {$this->tabela} WHERE idQUESTOES = :id",array(':id'=>$id),FALSE);

 }

 // Retorna uma questão a partir de uma pesquisa
 public function getLike($busca)
 {
    return $this->db->select("SELECT * FROM {$this->tabela} WHERE QUESTOES LIKE :busca",array(':busca'=>$busca));
 }

 // Remove uma questão
 public function remove($id)
 {
    $id = (int)$id;
    return $this->db->delete($this->tabela,"idQUESTOES = '$id'");
 }

 public function cadastrarQuestoes(Questoes $questoes)
 {
    $valores = array('QUESTOES'=>$questoes->getQuestoes(),'DESCR_QUESTOES'=>$questoes->getDescQuestoes(),'ORDEM'=>$questoes->getOrdem());

    return $this->db->insert($this->tabela, $valores);
 }

 public function preencheGrid()
 {
    return $this->db->select("SELECT id as idQUESTOES,
                                     QUESTÃO as QUESTOES,
                                     DESCR_QUESTOES as DESCR_QUESTOES FROM
                                     {$this->tabela}");
 }



 public function atualizar(Questoes $questoes)
 {
    $valores = array('idQUESTOES'=>$questoes->getId(),
            'QUESTOES'=>$questoes->getQuestoes(),
            'DESCR_QUESTOES'=>$questoes->getDescQuestoes(),
            'ORDEM'=>$questoes->getOrdem()
    );

    $where = "idQUESTOES = " . (int) $questoes->getId();

    //Executa a operação

    return $this->db->update($this->tabela, $valores, $where);
 }
}

Questoescontroller.php

<?php
require_once("../model/pojo/Questoes.php");
require_once("../model/dao/QuestoesDAO.php");


class QuestoesController {

private $dao;
private $questoes;
public $retorno;
public $fieldvalue;



public function __construct() 
{
    $this->dao = new QuestoesDAO();
    $this->questoes = new Questoes();

    if (isset($_GET['action'])) {
        if ($_GET['action'] == 'alterar') {
            $this->showDadosForm();
        }   
        else if ($_GET['action'] =='remover') {
            $this->remover();
        }

    }

    if( $_SERVER['REQUEST_METHOD'] == 'POST'){
        $acao = $_POST['action'];
        if ($acao =='inserir') {
            $this->inserir();
        }
        else
            if ($acao =='alterar') {
                $this->alterar();
            }
    }


}



public function inserir() {
    $this->recebeDados();
    $cadastrou = $this->dao->cadastrarQuestoes($this->questoes);
    if ($cadastrou) {
        $this->retorno = "<div class='alert alert-success'>
                <button type='button' class='close' data-dismiss='alert'>&times;</button>
                <strong>Sucess!</strong> Questão inserido com sucesso!
                </div>";
    }
    else {
        $this->retorno = "<div class='alert alert-success'>
                <button type='button' class='close' data-dismiss='alert'>&times;</button>
                <strong>Sucess!</strong> Erro ao inserir questão!
                </div>";
    }

    return $this->retorno;
}

public function alterar() {
    $this->recebeDados();
    $this->questoes->setId($_POST['id']);

    if ($this->dao->atualizar($this->questoes)) {
        $this->retorno = "<div class='alert alert-success'>
                <button type='button' class='close' data-dismiss='alert'>&times;</button>
                <strong>Sucess!</strong> Questão alterada com sucesso!
                </div>";
    }

    else {
        $this->retorno = "<div class='alert alert-success'>
                <button type='button' class='close' data-dismiss='alert'>&times;</button>
                <strong>Sucess!</strong> Erro ao alterar questão!
                </div>";
    }

}

public function preencheGrid()
{
    return $this->dao->preencheGrid();
}

public function getAll()
{
    return $this->dao->getAll();
}

public function showDadosForm()
{
    $id = $_GET['id'];
    $this->fieldvalue = $this->dao->getById($id);
    //var_dump($this->fieldvalue);
}

public function recebeDados()
{
    $this->questoes->setQuestoes($_POST['txt_questao']);
    $this->questoes->setDescQuestoes($_POST['desc_questao']);
    $this->questoes->setOrdem($_POST['ordem']);
}

public function remover() 
{
    $id = $_GET['id'];
    return $this->dao->remove($id);
}


public function chamaFormulario()
{
    $list = $this->dao->getAll();

    foreach($list as $questoes) {
        $valores = array('idQUESTAO1'=> '1' , 'QUESTOES1'=>'O que vc acha dos serviços prestados pela nossa empresa?','DESC_QUESTAO1'=>'primeira questao','ORDEM1'=>'1',
          'idQUESTOES2'=>'2','QUESTOES2'=>'Como vc analisa a empresa','DESC_QUESTAO2'=>'segunda questao','ORDEM2'=>'2'                  
        );

    }

    return $valores['QUESTOES1']."<br/><br/>";

}   

}

$class = new QuestoesController();

Well in the call methodFormular I created an associative array in it I need to specify table fields questoes

idQuestoes=>'1','QUESTOES'=>$questoes[field1databelaaqui]<------how do I get a given field from the table.

tabela questoes

questionario.php

<?php 

require_once("../controller/QuestoesController.php");
require_once ("../controller/RespostasController.php");
require_once ("../controller/OpcoesController.php");
$crt_questoes = new QuestoesController();
$list=$crt_questoes->getAll();
$crt_opcoes = new OpcoesController();
$lista = $crt_opcoes->getAll();

?>

<!DOCTYPE html>
<html>
 <head>
     <title> Saqc - Sistema de Avaliação de Qualidade do Cliente </title>
     <meta charset="utf-8" />
     <link rel="stylesheet" type="text/css" href="css/estilo.css" />
 </head>
 <body>

  <div class="questionario">
  <form action="questionario.php&action=inserir" method="POST">

  <input type="hidden" name="action" value="<?php echo $_GET['action']; ?>" >
     <h1> Questionario </h1>
     <table>
     <thead>
     </thead>
     <tbody>

     <tr>
      <td>
         <?php echo $crt_questoes->chamaFormulario(); ?>
      <input type="radio" name="opcao" id="opcao1" value="<?php $valores['idQUESTOES']?>"> Otimo <br />
      <input type="radio" name="opcao" id="opcao2" value="<?php ?>"> Bom   <br />
      <input type="radio" name="opcao" id="opcao3" value="<?php ?>"> Regular <br />
      <input type="radio" name="opcao" id="opcao4" value="<?php ?>"> Ruim <br />
      </td>
     </tr>

     <tr>
      <td style="background: #FFF; border: 0"> <input type="submit" name="Enviar" value="Enviar" /> </td>
     </tr>
     </tbody>
     </table>


     </form>

  </div>

 </body>
</html>
  • shows how your array is coming

  • What do you want to do? I didn’t understand.

  • 1

    You want to iterate the object containing the return method fetchAll ? Your class methods seem to have several logic problems as well - $this->dao->getAll(); and the method getAll() is the same as himself, being unnecessary.

  • I don’t understand anything @rray

  • 1

    Suspended question because I reformulated the database and there is really no answer here.

2 answers

-2


You can do so, the $d variable you will use the array you created. Example, this way will work.

<?php
//array
$d = $arrayName = array('A' => 1,'B'=>2 );

foreach ($d as $key => $value) {
    echo $key.'=>'.$value.'<br>';
}
/*
vai imprimir isso
chave A=> valor 1
chave B=> valor 2
*/
?>
  • 1

    right but I want to take the column QUESTOES look at the table image of the bank I want it to stay like this array('idQuestoes'=>'1','Questoes1'=>$questoes['What do you think of the services provided by our company? ']<<thus does not work

  • the variable $d will change and will put the variaval of your array, the $key is key that is idQuestos and $value the value 1, and so in dianta, it will do this with how many settlers are coming in the return array of the query, this example I showed you will work, only renames the $d variable to the name of the array variable.

  • 1

    I redid the database, the way it was too complex to develop the vlw system by the help..

-2

I just printed, but then you can do the processing as you need the data return, whether it is in array form or just printing.

<?php
public function getAll()
{
    //array
    $d =  $this->dao->getAll();
    foreach ($d as $key => $value) {
        echo $key.'=>'.$value.'<br>';
    }
}

/*
vai imprimir isso
idQuestoes=>1
QUESTOES=> questoes
*/
?>
  • OK let me explain better

  • Stackoverflow is different from a forum see how the dynamics in tour

  • 2

    The answers of rray and HENRIQUE are enough, Carlos..

Browser other questions tagged

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