How do I display the customer name of a particular sale? I’m not getting the name with get

Asked

Viewed 233 times

8

sales list code I’m having trouble presenting the customer name of each sale and product name of each sale tbm! I don’t know what I’m doing wrong

<?php
  include_once("Sessao.php");
  include_once("Valida.php");
  include_once("Cabecalho.php");

 include_once './Classes/Singleton.php';

 include_once './Classes/Venda.php';
 include_once './Classes/VendaDao.php';

 // include_once 'Classes/Cliente.php';
 // include_once 'Classes/ClienteDao.php';
// include_once 'Classes/Produto.php';
// include_once 'Classes/ProdutoDao.php';?>

<?php 
    if($_GET && $_GET["msg"] && $_GET["tpMsg"]){
 ?>
    <div class="alert alert-<?php echo $_GET["tpMsg"] ?>" role="alert">
        <strong>Atenção: </strong><?php echo $_GET["msg"]?>
    </div>
<?php 
    }
 ?>

<div>   
   <a class="btn btn-success" href="FormVenda.php"> Novo Venda </a>
</div>

   <hr>

 <div>
   <table class="table table-striped table-hover">
    <thead>
        <tr>
            <th> Código </th>
            <th> Data </th>
            <th> Cliente </th>
            <th> Produto </th>
            <th> Quantidade </th>                
            <th> Preço </th>                
            <th> Total </th>                
            <th> Ações </th>
        </tr>
    </thead>
    <tbody>
        <?php

        $vendaDao = new VendaDao();
        $lista = $vendaDao->listar();

        foreach ($lista as $venda) {

            //$urlAlterar = "FormVenda.php?comando=U&codigo={$venda->getCodigo()}";
            $urlExcluir = "FormVenda.php?comando=D&codigo={$venda->getCodigo()}";
            $urlExcluir = "JavaScript:if(confirm('Deseja realmente excluir o venda?')) { document.location.href='{$urlExcluir}' }";

            echo
            "<tr>
                <td> {$venda->getCodigo()} </td>
                <td> {$venda->getData()} </td>
                <td> {$venda->getCliente()->getNome()} </td>
                <td> {$venda->getProduto()->getNome()} </td>
                <td> {$venda->getQuantidade()} </td>

                <td>
                    <a class='btn btn-danger' href=\"{$urlExcluir}\"> Excluir </a>
                </td>
            </tr>";
        }

        ?>

    </tbody>
</table>

 </div>
    <!-- <td> R$ {$venda->getProduto()->getPreco()} </td>
   <td> R$ " . ($venda->getPreco() * $venda->getQuantidade()) . " </td> -->
<?php

class VendaDao {

    private $pdo = null;

    public function __construct(){
        //pegar instancia e atribuir $pdo

        $this->pdo = Singleton::getInstance()->getPDO();
    }


    public function salvar(Venda $venda){
        //aqui dentro sempre vira um objeto

        if( !$venda->getCodigo() ){

            $sql = "INSERT INTO venda(data, quantidade, cliente, produto)
            VALUES(:data, :quantidade, :cliente, :produto)";

             $resultado = $this->pdo->prepare($sql);

        } else {

             $sql = "UPDATE venda SET data=:data, quantidade=:quantidade, cliente=:cliente,
                 produto=:produto WHERE codigo=:codigo";

             $resultado = $this->pdo->prepare($sql);
             $resultado->bindValue(":codigo",$venda->getCodigo(),PDO::PARAM_INT);
        }

            $resultado->bindValue(":data",$venda->getData(),PDO::PARAM_STR);
            $resultado->bindValue(":quantidade",$venda->getQuantidade(),PDO::PARAM_INT);
            $resultado->bindValue(":cliente",$venda->getCliente(),PDO::PARAM_INT);
            $resultado->bindValue(":produto",$venda->getProduto(),PDO::PARAM_INT);

                 $resultado->execute();
    }


    public function excluir($codigo){
        $sql = "DELETE FROM venda WHERE codigo=:codigo";
        $resultado = $this->pdo->prepare($sql);
        $resultado->bindValue(":codigo",$codigo,PDO::PARAM_INT);
        $resultado->execute();

        return $resultado->rowCount() ==1;

    }

    public function listar(){
        $vendas = array();



        $sql = "SELECT codigo, data, quantidade, cliente, produto, 'c.nome', 'p.nome' FROM venda as v 
        INNER JOIN cliente c ON 'c.codigoCli' = 'v.cliente' 
        INNER JOIN produto p ON 'p.codigoPro' = 'v.produto' 
        ORDER BY data";
        $resultado = $this->pdo->prepare($sql);
        $resultado->execute();

        while( $vendaBD = $resultado->fetch(PDO::FETCH_OBJ) ){

            $venda = new Venda();
            $venda->setCodigo($vendaBD->codigo);
            $venda->setData($vendaBD->data);
            $venda->setQuantidade($vendaBD->quantidade);

            $c = new Cliente();
            $c->setCodigoCli($vendaBD->codigoCli);
            $c->setNome($vendaBD->nome);
            $venda->setCliente($c);

            $p = new Produto();
            $p->setCodigoPro($vendaBD->codigoPro);
            $p->setNome($vendaBD->nome);
            $venda->setProduto($p);


        $vendas[] = $venda;
        print_r($vendas);

   }

        return $vendas;


        }
  }


 ?>
  • 1

    You can show the source code of VendaDao()?

  • 1

    Welcome to Stack Overflow Amanda! Prefer to post the code in text, so it’s easier for someone who wants to answer reproduce their problem.

  • You can show the class code of your Sale.

  • Instead of the name comes the code?

  • yes the client code appears but not the name

  • When you call getCliente() what appears?

  • when I call getCliente() the client code appears and when I put in front getNome() of the error

  • Which error appears?

  • Fatal error: Call to a Member Function getNome() on a non-object

  • edited the response code.

  • Does your user have a name in the database? Because there is an error, it is because there is no instance of the name.

  • What happens when you make one var_dump($venda); within your foreach()?

  • try something like: get_class_methods ( $venda );

Show 8 more comments

2 answers

1

The problem seems to be your table venda the fields cliente and produto are not descriptions like john and coffee, are ids so when calling getCliente() a number is displayed.

To fix this it is necessary to make two joins one for customer and another for product to get their descriptions. If fields have the same names in different tables use an alias to avoid overwriting values in php.

Done this just create the customer and product objects and set their values.

Your query should look more or less like this, adjust the field names.

SELECT codigo, data, quantidade, cliente, produto,
       c.nome as nome_cliente, p.nome as nome_produto
    FROM venda as v 
    INNER JOIN cliente c ON c.codigoCli = v.cliente
    INNER JOIN produto p ON p.codigoPro = v.produto 
ORDER BY dat

Now no while create customer and product object

while( $vendaBD = $resultado->fetch(PDO::FETCH_OBJ) ){

    $venda = new venda();
    $venda->setCodigo($vendaBD->codigo);
    $venda->setData($vendaBD->data);
    $venda->setQuantidade($vendaBD->quantidade);

    $c = new Cliente();
    $c->setId($vendaBD->cliente);
    $c->setNome($vendaBD->nome_cliente);

    $venda->setCliente($c);

    $p = new Produto();
    $p->setId($vendaBD->produto);
    $p->setNomeProduto($vendaBD->nome_produto);
    $venda->setProduto($p);


    $vendas[] = $venda;
}
return $vendas;

1

From what I can see, the error is more banal than it seems. You are quoting and do not have to put this in your query query and test using same name for product and for name, in this case create a alias. Do as below:

 $sql = "SELECT 
          codigo,
          data,
          quantidade,
          cliente,
          produto,
          IF(c.nome == NULL,'Nome não informado',c.nome) as nome,
          IF(p.nome == NULL,'Nome do produto não informado',c.nome) as nome_produto
        FROM venda as v 
        INNER JOIN cliente c ON (c.codigoCli = v.cliente) 
        INNER JOIN produto p ON (p.codigoPro = v.produto) 
        ORDER BY data";

Change the field date for data_reg, so you avoid SQL errors, because the word date is reserved from Mysql.

OBS: When you quote in the field type: 'c.name', it is the same as saying that you built a string value "c.name", and not that your field is called name. But you can quote your alias, because it’s a name association, and especially when the alias requires a space. Something like Select c.nome AS 'Nome de Usuário' from tabela. You could also create a fictional field in this same way by placing a type value: SELECT 0 as Zero from tabela, or SELECT 'Amanda' as Nome from tabela, that it would create the Zero column with value 0 and create the Name column with value Amanda.

And where you arrow the product name, you have to change with the alias call:

$p->setNome($vendaBD->nome_produto);
  • I’ll try! Thank you must be this msm

  • so, I quote pq without them from error saying that it does not find the customer class so I put and not give more error just no list

  • So then you understand why there is no error? Because you are filling the field with a fake value.

  • Change the date field and see if it will stop the problem.

  • yes, I get it! I’ll change

  • Do a test, just run it on the Workbench or phpmyadmin: select 'a.nome' as Nome; or select 'a.nome' as 'Nome do cara';

  • Another thing, as you changed the alias, now you have to call it in place. $p->setNome($vendaBD->nome_produto);

  • I will make a small edit, so that your instance never returns with error if there is no value in one of the fields.

  • I got it!! I removed the quotes and put alias as you said and it worked. Thank you so much for the help

Show 4 more comments

Browser other questions tagged

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