How to send more than one value through return

0

I am performing a query in the database and want to return more than one query value how do I do this?

The structure of my table and the following

Id_idx | name | OUTROS |

Each Id_idx can be repeated up to 3 times I want to count how many rows are returned which is the first part of code and also returns the values of the other columns.

Here it will only return the number of rows.

$char = $pdoG->prepare("SELECT * FROM u_hero WHERE id_idx = :id");
$char->bindValue(":id",$id);
$char->execute();
$chars = $char->rowCount();
return $chars;

While here, the information is returned to me.

$char = $pdoG->prepare("SELECT * FROM u_hero WHERE id_idx = :id");
$char->bindValue(":id",$id);
$char->execute();
$chars = $char->fetchAll(PDO::FETCH_OBJ);
return $chars;

How do I merge these return into a single static function ?

    
asked by anonymous 10.12.2017 / 22:46

1 answer

4

You can use an array in return :

$char = $pdoG->prepare("SELECT * FROM u_hero WHERE id_idx = :id");
$char->bindValue(":id",$id);
$char->execute();

return array(
    'datos' => $char->fetchAll(PDO::FETCH_OBJ);
    'total' => $char->rowCount()
);

When the function returns you can iterate the data, something like:

Total: <?php echo $variavel['total']; ?><br>

<!-- vai iterar os resultados -->
<?php foreach ($variavel['dados'] as $linha): ?>

    <!-- vai iterar os valores por coluna -->
    <?php foreach ($linha as $coluna => $valorColuna): ?>
    <?php echo $coluna, ': ', $valorColuna; ?><br>
    <?php endforeach; ?>

<?php endforeach; ?>

If you want to query more than one ID you can do this:

function minhaFuncao(array $ids) {
    $query = str_repeat('id_idx = ? OR ', count($ids));
    $query = substr($query, 0, -4);//Remove o OR extra do final

    $char = $pdoG->prepare("SELECT * FROM u_hero WHERE " . $query);

    foreach ($ids as $id) {
        $char->bindValue(1, $id);
    }

    $char->execute();

    return $char->fetchAll(PDO::FETCH_OBJ);
}

And it would look like this:

$idsParaConsulta = array(
   1, 5, 8, 4, 20
);

print_r(minhaFuncao($idsParaConsulta));

    
10.12.2017 / 22:54