Why is my foreach duplicating my database records?

-2
function DBRead($table, $params = null, $fields = '*'){
    $table  = DB_PREFIX.'_'.$table;
    $params = ($params) ? " {$params}" : null;

    $query  = "SELECT {$fields} FROM {$table}{$params}";
    $result = DBExecute($query);

    if(!mysqli_num_rows($result))
        return false;
    else{
        while ($res = mysqli_fetch_assoc($result)){
            $data[] = $res;
        }
        return $data;
    }
}

$publicacao = DBRead('publicacao');
    foreach ($publicacao as $pl):
    endforeach;

    <?php foreach ($publicacao as $pl): ?>
        <li>
            <h4><a href="#"><?php echo $pl['title']?></a></h4>

            <h5><?php echo $pl['text']?><a href="%">Continue lendo &raquo;</a></h5>
        </li>
    <?php endforeach; ?>

    <?php foreach ($publicacao as $pl): ?>
        <li>
            <h4><a href="#"><?php echo $pl['title']?></a></h4>

            <h5><?php echo $pl['text']?><a href="%">Continue lendo &raquo;</a></h5>
        </li>
    <?php endforeach; ?>

I put a print_r ($ publication) between the line $ publicacao = DBRead ('publication'); and foreach ($ publication as $ pl) : Result is below:

Array ( [0] => Array ( [id] => 33 [title] => First Title [text] => First Text ) [1] => Array ( [id] => 34 [title] => Second Title [text] => Second Text ) )

The print_r ($ publication) that I placed between foreach ($ publication as $ pl): and endforeach; the result is this:

Array ( [0] => Array ( [id] => 33 [title] => First Title [text] => First Text ) [1] => Array ( [id] => 34 [title] => Second Title [text] => Second Text ) ) Array ( [0] => Array ( [id] => 33 [title] => First Title [text] => First Text ) [1] => Array ( [id] => 34 [title] => Second Title [text] => Second Text ) )

In my database I only have 2 records. Why is it duplicated?

    
asked by anonymous 05.09.2018 / 22:12

1 answer

2

Do so, foreach will execute as many times as necessary until you get to the end of the returned array (amount of your records) so those 3 foreach are not needed. Just remove the other 2

function DBRead($table, $params = null, $fields = '*'){
    $table  = DB_PREFIX.'_'.$table;
    $params = ($params) ? " {$params}" : null;

    $query  = "SELECT {$fields} FROM {$table}{$params}";
    $result = DBExecute($query);

    if(!mysqli_num_rows($result))
        return false;
    else{
        while ($res = mysqli_fetch_assoc($result)){
            $data[] = $res;
        }
        return $data;
    }
}

$publicacao = DBRead('publicacao');

    <?php foreach ($publicacao as $pl): ?>
        <li>
            <h4><a href="#"><?php echo $pl['title']?></a></h4>

            <h5><?php echo $pl['text']?><a href="%">Continue lendo &raquo;</a></h5>
        </li>
    <?php endforeach; ?>
    
05.09.2018 / 22:23