PHP Dynamic Function

Asked

Viewed 196 times

0

How do I rework this function to make a select in more than one table, dynamically ?

  public function Lista(){
        $results = array();
        $stmt = $this->conn->prepare("SELECT * FROM 'tabela'");
        $stmt->execute();
            if($stmt) {
                while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
                    $not = new Not();
                    $not->setid($row->ID);
                    $not->setimg1($row->Img1);
                    $not->setimg2($row->Img2);
                    $not->setimg3($row->Img3);
                    $results[] = $not;
                }
            }
        return $results;
    }

Because I need several select’s in several tables I could not find a simple way, except to make a function for each select. The same is repeated for update and insert. Any hint ?

  • 1

    Have you considered moving to the function the table name as argument? no prepare you do something like that: "SELECT * FROM '$nomeTabela'".

  • Search for Inner Join or Union

1 answer

2


I believe you want something like this.

 public function Lista($tabela){
        $sql = "SELECT * FROM '$tabela'";
        $results = array();
        $stmt = $this->conn->prepare($sql);
        $stmt->execute();
            if($stmt) {
                while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
                    $not = new Not();
                    $not->setid($row->ID);
                    $not->setimg1($row->Img1);
                    $not->setimg2($row->Img2);
                    $not->setimg3($row->Img3);
                    $results[] = $not;
                }
            }
        return $results;
    }

To pass the value of the table, just write its name when calling the function List() as in the example below:

Lista('usuario');

Thus the function returns data from the user table

  • I get it, how do I pass a value to this $tabela ?

  • I edited the question with an example

Browser other questions tagged

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