select with Pdo in functions

Asked

Viewed 396 times

1

How do I use my select in mine funções.php in this table that is in my estoque.php , I’ve done the script just can’t call the $resultado that this in the function to use in the foreach.

STOCK.PHP

    selecionar_produtos();

?>  

<div class="container">
    <div class="table-responsive">
    <table class="table">
        <thead>

            <tr>

                <th>Nome</th>
                <th>Marca</th>
                <th>Modelo</th>
                <th>Quantidade</th>
                <th>Estado</th>
                <th>Opções</th>

            </tr>

        </thead>

        <tbody>

        <?php foreach ($resultado as $key) :?>

            <tr>

                <td><?php echo $key->nome;?></td>
                <td><?php echo $key->marca;?></td>
                <td><?php echo $key->modelo;?></td>
                <td><?php echo $key->quantidade;?></td>
                <td><?php echo $key->estado;?></td>
                <td>
                    <a href="mysql/update.php?id=<?php echo $key->id; ?>" class="btn btn-info">Editar</a>

                    <a href="mysql/delete.php?id=<?php echo $key->id; ?>" class="btn btn-danger">Deletar</a>

                </td>

            </tr>

            <?php endforeach;?>

PHP FUNCTIONS.

    <?php

    function selecionar_produtos(){

    require "mysql/pdo.php";

    try{

        $selecionar = "select * from estoqueprodutos . produtos";

        $stmt = $pdo->prepare($selecionar);

        $stmt->execute();

        $resultado = $stmt->fetchAll(PDO::FETCH_OBJ);


    } catch (PDOException $error){
        echo "Erro:\n" . $error->getMessage();  
    }
    }
    ?>

1 answer

3

Its function does not return anything so it is not possible to receive anything in the function call, add a return.

$resultado = $stmt->fetchAll(PDO::FETCH_OBJ);
return $resultado;

With the function returning the bank records fingers make an assignment, because the varive $resultado exists only within the function selecionar_produtos() after his call he does not exist.

$produtos = selecionar_produtos();
//código omitido
<?php foreach ($produtos as $key) :?>
  • Thanks for the help :)

  • @felipemarques, when you need it

Browser other questions tagged

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