Outputing same DB results twice

Hello,

How I can output same DB results twice?

E.g

while ($result = $db->fetch(PDO:FETCH_OBJ) {
    echo $db->Fname . '<br>';
    echo $db->Lname . '<br>';
}

And now I want to use same results somewhere else on same page, should I store them in array within while loop or there is other way to do it?

Store the values in an array, an object, or just plain variables, whatever fits your needs, then echo out wherever needed.

1 Like

Like Sam said store it in a variable and you can reuse it anywhere

$result = $db->fetch(PDO:FETCH_OBJ);

/* First instance */
echo $result->Fname . '<br>';
echo $result->Lname . '<br>';

/* Second instance */
echo $result->Fname . '<br>';
echo $result->Lname . '<br>';
1 Like

@jacobchen17 $result is an object, not an array! while count() will work, the loop will fail.

1 Like

Thanks for the correction. I amended my post

while is outdated

get your data into a conventional array first and then you’'l be able to use it anywhere and anytime

$data = $db->fetchAll(PDO:FETCH_OBJ);
foreach ($data as $result)
    echo $result->Fname . '<br>';
    echo $result->Lname . '<br>';
}
1 Like

I don’t consider the while statement outdated, but that’s my opinion.

While the following is done is done in OOP this can be easily translated into procedural style. Well after I explain it first.

    public function read($page_name, $column_pos) {
        $db = DB::getInstance();
        $pdo = $db->getConnection();
        $this->query = 'SELECT id, user_id, page_name, column_pos, image_path, heading, content, DATE_FORMAT(date_added, "%W, %M %e, %Y") as date_added FROM cms WHERE page_name=:page_name and column_pos=:column_pos';

        $this->stmt = $pdo->prepare($this->query); // Prepare the query:
        $this->stmt->execute([':page_name' => $page_name, ':column_pos' => $column_pos]); // Execute the query with the supplied user's parameter(s):
        return $this->stmt;
    }

the main thing is the $this->stmt which in procedural style would be $stmt. This basically sets up collection of records that you queried. $this->query ($query)

next you do this to display:

    public function display() {
        while ($this->row = $this->stmt->fetch(PDO::FETCH_OBJ)) {
            echo '<article class="content">' . "\n";
            if ($this->row->heading) {
                echo "<h1>" . htmlspecialchars($this->row->heading) . '<span class="date_added">Created on ' . $this->row->date_added . '</span></h1>' . "\n";
            } 
            if (isset($_SESSION['user']) && ($_SESSION['user']->security_level === 'sysop' || $_SESSION['user']->user_id === $this->row->user_id)) {
                echo '<a class="editBtn" href="edit_page.php?id=' . urlencode($this->row->id) . '">Edit</a>' . "\n";
            }

            if ($this->row->image_path) {
                echo '<figure class="imageStyle">' . "\n";
                echo '<img src="' . htmlspecialchars($this->row->image_path) . '" alt="' . htmlspecialchars($this->row->heading) . '">' . "\n";
                echo '<figcaption>&nbsp;</figcaption>' . "\n";
                echo "</figure>\n";
            }
            echo "<p>" . htmlspecialchars($this->row->content) . "</p>\n";
            echo "</article>\n";
        }
    }

you would create a procedural function such as an example function display($stmt) { and call it like

display($stmt);

after retrieving the records like $stmt = read(“index.php”, “left”); this is just an example with pseudo code thrown in explaining it better for procedural. I like writing in OOP for if I want to change my HTML, then I just have to replace my Display class with another Display class and leave my Read class (an abstract class) the way it was (or vice versa if I want to change my data structure). Anyways sorry for my rambling, but my point is you could do this in procedural style and call it as many times you want on your page. You can even have a function call another function thus doing it the same way in procedural cide.

For example if you want call the same output more than once on a page then something like the following can be done.

display($data);
/* More Code or HTML */
display($data);

I hope I explained myself clear or at least gave you some ideas how it could be done. There’s are many ways to do this and everyone has a different technique. That is what makes coding so fun.

I appreciate the feelings but for some reason you completely missed the question asked here.
Which made your answer not that good as it could be. For example, nowhere $stmt is a collection but a resource. Whereas a function called read() indeed should return a collection. Were you made it return fetchAll() result, it would have been a perfect function, allowing a programmer to iterate over a context independent collection using foreach instead of meddling with while over a resource tightly coupled to the database.

with fetch then you are locked into that data no matter what. This is just a simple script, you way would probably be the best. However, if you were displaying the same data over gain then decide to that you want to do something different with the data (or add something) then you are locked in with that data and playing around with with if statements and loops, whereas do this way you’re not tied into doing that and you’re letting MySQL do the work. Basically my way is a simplistic approach to MVC (Model View Controller). $stmt is not a resource but basically a model/controller. You have a database in my opinion you might well use it. Like I said many different approaches to writing a script.

Unfortunately, your approach is far from MVC, again for returning a database specific resource, violating single responsibility principle. A View should be able to display a data from any source whereas yours is coupled to a database.
Not to mention that running a query again to display the same data is a nonsense.

Returning a statement is a good thing, bit only for a database-related function. So a better variant of your approach will be

public function read($page_name, $column_pos) {
    $query = 'SELECT id, user_id, page_name, column_pos, image_path, heading, content,
                    DATE_FORMAT(date_added, "%W, %M %e, %Y") as date_added 
                    FROM cms WHERE page_name=? and column_pos=?';
    return DB::run($query, [$page_name, $column_pos])->fetchAll();
}

here, a database-related function run() is responsible for running your query and meddling with binding and stuff. It is appropriate for it to return a statement. You see, every function here is doing it’s hob. That’s MVC for real

By the way. make sure that your alleged database wrapper is not like this one (as it looks quite similar):

I have a stupid question shouldn’t the line be

return DB::run($query, [$page_name, $column_pos])-&gt;fetchAll();

? Just a little confused on that part.

and to answer your question - no my database wrapper is not like that, for it’s uses the singleton approach that I learned from a book by Larry Ullman which only allows for one connection.

It got me thinking wouldn’t your way not have to use even a loop? Never mind I had a brainfart…

You are absolutely right! Fixed that issue.

By the way, my code is still not a true MVC as it is using a singleton for a database access. To make it Orthodox MVC it should be provided from a class variable instantiated in a controller.

Thank you very much guys!
I have one question unrelated to topic, why singletons are still popular in db connecting? I tought that DI replaced singleton aproach.

Because they are highly convenient and at the same time PHP users en masse are not quite familiar with OOP. And without a proper class structure it’s hard to make a viable DI

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.