PDO: Cost of Calling prepare() in a loop?

南笙酒味 提交于 2019-12-01 04:54:39

问题


I'm writing a database class for my website with functions such as fetchOne, fetchAll which prepare, execute (+ bind), and fetch the query all in one so I don't have to individually call those functions every time. Some cron jobs on my site execute thousands, or even millions of queries inside of a loop.

Would using my class cause the statement to be re-prepared each iteration of the loop or would PDO "remember" the query has already been prepared? Would this significantly impact performance and if so could the solution be to just provide a function that passes the database instance and do something like $db->getDb()->prepare($query); outside of the loop? Or is there a better solution?

Example function:

public function fetchOne($query, $params = array(), $fetchMode = PDO::FETCH_ASSOC)
{
    $stmt = self::prepareExecute($query, $params);

    $result = $stmt->fetch($fetchMode);
    if (count($result) < 1)
        $result = FALSE;

    $stmt->closeCursor();
    unset($stmt);
    return($result);
}

回答1:


you would not want to "re-prepare" the same query multiple times. this is the purpose of the prepare statement. you prepare it once, bind the variable(s), then you simply switch the variables' values and re-execute each iteration of the loop.

http://www.php.net/manual/en/pdostatement.bindparam.php

doing it this way will greatly increase your performance over alternative methods.



来源:https://stackoverflow.com/questions/9168562/pdo-cost-of-calling-prepare-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!