Code
Code

Reputation: 25

While with variable

I am trying to make a while with only variable from function.

This is my listing pages code and it works.

$pages_table = $connect->prepare('SELECT * FROM pages');
$pages_table->execute();

while($pages_list = $pages_table->fetch(PDO::FETCH_ASSOC)) {
    echo $pages_list['name'];
}

But i want to this one and it is not working.

function page_list() {
    global $connect;
    $pages_table = $connect->prepare('SELECT * FROM pages');
    $pages_table->execute();
    return $pages_list = $pages_table->fetch(PDO::FETCH_ASSOC);
}
while (page_list()) {
    echo $pages_list['name'];
}

Can you help me?

Upvotes: 1

Views: 31

Answers (1)

Syscall
Syscall

Reputation: 19779

That's because each time you call page_list(), you are executing a new query.

You could:

  1. Return the statement:

    function page_list() {
        global $connect;
        $pages_table = $connect->prepare('SELECT * FROM pages');
        $pages_table->execute();
        return $pages_table ;
    }
    
    $pages_table = page_list();
    while ($pages_list = $pages_table->fetch(PDO::FETCH_ASSOC)) {
        echo $pages_list['name'];
    }
    
  2. Or use fetchAll() and foreach():

    function page_list() {
        global $connect;
        $pages_table = $connect->prepare('SELECT * FROM pages');
        $pages_table->execute();
        return $pages_table->fetchAll(PDO::FETCH_ASSOC) ;
    }
    
    foreach (page_list() as $pages_list) {
        echo $pages_list['name'];
    }
    
  3. Or using generators with yield (since PHP 5.5):

    function page_list() {
        global $connect;
        $pages_table = $connect->prepare('SELECT * FROM pages');
        $pages_table->execute();
        while($row = $pages_table->fetch(PDO::FETCH_ASSOC)) { yield $row; }
    }
    
    foreach (page_list() as $pages_list) {
        echo $pages_list['name'];
    }
    

Upvotes: 1

Related Questions