select all records from the table stored in a Session

Asked

Viewed 19 times

1

I want to store all the records of my tables within a session, when I call my records it only pulls 1 result

class CRUD extends Config {

    private $query;

    private function prepExec($prep, $exec) {

        $this->query = $this->getConn()->prepare($prep);
        $this->query->execute($exec);

    }

    public function select($fields, $table, $prep, $exec) {

        $this->prepExec("SELECT ".$fields." FROM ".$table." ".$prep."", $exec);
        return $this->query;

    }

}

tried so

index php.

session_start();
$not = $crd->select('*', 'noticias', 'ORDER BY id DESC', array());
foreach ($not as $reg) :
    $_SESSION['slug_noticia'] = $not['slug_noticia'];
    $_SESSION['nome_noticia'] = $not['nome_noticia'];
endforeach;

and so

$not = $crd->select('*', 'noticias', 'ORDER BY id DESC', array());
foreach ($not as $reg) :
    $_SESSION['reg'] = $reg;
endforeach;

1 answer

2


If you want to create an array of records within the session, you would need to do so:

session_start();
$not = $crd->select('*', 'noticias', 'ORDER BY id DESC', array());
foreach ($not as $key => $reg) :
    $_SESSION['slug_noticia'][$key] = $not['slug_noticia'];
    $_SESSION['nome_noticia'][$key] = $not['nome_noticia'];
endforeach

The way you currently do, you assign a value in a loop iteration, but in the next iteration you override it, since you have not set any index in your assignment to create the "list".

In addition, you can simplify this stretch of foreach to generate a centralization of data in a session index only:

Example:

session_start();

$not = $crd->select('*', 'noticias', 'ORDER BY id DESC', array());
foreach ($not as $reg) {
    $_SESSION['noticias'][] = $not;
}

The operator [] is intended to add new "end" items to the array as it is called.

As a hint, in this last example, you could further improve your attribution using news id as index:

 $_SESSION['noticias'][$not['id']] = $not;

To recover session values later, you can make a foreach:

if (isset($_SESSION['noticias'])) {

    foreach ($_SESSION['noticias'] as $id => $noticia) {
          echo $noticia['titulo'];
    }
}
  • man because? Cannot use object of type PDOStatement as array along those lines $_SESSION['noticias'][$not['id']] = $not;

  • @Mayron debugging is life... If you’re returning this, it’s because you didn’t turn the fetch of PDOStatment somewhere.

Browser other questions tagged

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