Can prepared record descriptors be stored in member variables?

I have a PHP class that processes data and stores it in a MySQL database. I use prepared statements via PDO for security reasons, when the data is saved, but since the class is large, these prepared statements are created inside various functions that are called thousands of times during the lifetime of an object (from one minute to thirty).

What is interesting to me is, if for some reason I couldn’t prepare the instructions in the class constructor and save the descriptors in the member variables in order to avoid preparing the instructions more than once.

Is there a reason this will not work? I don’t understand why not, but I have never seen this before, and it makes me wonder if this is for some reason not doing bad practice.


those. something like that:

Class MyClass {

    private stmt1;

    function __construct($dbh) {
        $this->stmt1 = $dbh->prepare('SELECT foo FROM bar WHERE foobar = :foobar');
    }

    private function doFoo() {
        $this->stmt1->execute(...)
        ...
    }
}
+4
source share
3 answers

I use prepared statements via PDO for security reasons, when the data is saved, but since the class is large, these prepared statements are created inside different functions that are thousands of times throughout the life of the object (from one minute to thirty).

, , : " ?" - ?

  • SELECT, , , , .
  • INSERT, , .

, , , :

, . , , , , , .

+8

. .

, ( MySQL) ( MySQL, PDO::ATTR_EMULATE_PREPARES).

. SQL . , , .

, . , PHP. PDO , . .

, PHP . , . ( ); ( ).

, - . , b- foo (bar):

select bar from foo order by bar limit ?

, ; , , ; , seq . . , , . , , , , , .

, , ORM, .

+2

, , :

[...] .

. , , SQL- - . , , .

:

private $statments = array();

public function getStatement($sql)
{
    if (! isset($this->statements[$sql])) {
        $this->statements[$sql] = $this->pdo->prepare($sql);
    }
    return $this->statements[$sql];
}

, SQL- .

But I would call it premature optimization, because your DBS query cache will most likely do it for you.

+1
source

All Articles