Return mysql result with function

2

I'm trying to list a database table using a function but I can not use it outside of function :

The HTML:

<tbody>
 <?php listar('empresa'); ?>
 <?php foreach ($row as $listar): ?>
    <tr>
        <td><?php echo $listar['id']; ?></td>
        <td><?php //echo $listar['titulo']; ?></td>
        <td><?php //echo $listar['texto']; ?></td>
        <td><?php //echo $listar['data']; ?></td>
        <td></td>
 <?php  endforeach; ?>
   </tr>
</tbody>

The call:

listar('empresa');

The function:

function listar($tabela, $campos="*", $onde=null, $filtro=null, $ordem=null, $limite=null) {
$pdo = conectar();
$sql = "SELECT $campos FROM $tabela";

if ($onde) {
    $sql .= " WHERE $onde";
}
elseif ($filtro) {
    $sql .= " WHERE $filtro";
}

if ($ordem) {
    $sql .= " ORDER BY $ordem";
}
if ($limite) {
    $sql .= " LIMIT $limite";
}
$query = $pdo->query($sql);
$query->execute();
$row = $query->fetchAll(PDO::FETCH_ASSOC);

print_r($query->errorInfo());
}

The output:

  

Notice: Undefined variable: row

     

Warning: Invalid argument supplied for foreach ()

    
asked by anonymous 10.08.2015 / 19:23

1 answer

2

At your% change%:

$row = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($query->errorInfo());

To:

$row = $query->fetchAll(PDO::FETCH_ASSOC);
return $row;

On your função do:

<tbody>
 <?php $listagem = listar('empresa'); ?>
 <?php foreach ($listagem as $listar): ?>
    <tr>
        <td><?php echo $listar['id']; ?></td>
        <td><?php //echo $listar['titulo']; ?></td>
        <td><?php //echo $listar['texto']; ?></td>
        <td><?php //echo $listar['data']; ?></td>
        <td></td>
 <?php  endforeach; ?>
   </tr>
</tbody>

Considering that you need to set a variable so that foreach does the search, you can not create one within the function and pass it directly on foreach .

This should solve your problem.

    
10.08.2015 / 19:51