Return mysql result with function

Asked

Viewed 682 times

2

I’m trying to list a database table using a function but I can’t use it outside the 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 exit:

Notice: Undefined variable: Row

Warning: Invalid argument supplied for foreach()

1 answer

2


In his função alter:

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

To:

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

In his foreach 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>

Whereas you need to set a variable so that the foreach do the search, can not create one within the function and pass it directly in the foreach.

This should solve your problem.

Browser other questions tagged

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