问题
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