php - Benefiting from PDO Prepared statement when used in a function or method -
per http://php.net/manual/en/pdo.prepared-statements.php
the query needs parsed (or prepared) once, can executed multiple times same or different parameters. when query prepared, database analyze, compile , optimize plan executing query. complex queries process can take enough time noticeably slow down application if there need repeat same query many times different parameters. using prepared statement application avoids repeating analyze/compile/optimize cycle. means prepared statements use fewer resources , run faster.
as such, following benefit improved performance when using prepared statements:
<?php ... $stmt=$conn->prepare('select mytable x=?'); //i use globals or similar $conn foreach($array $id){ $stmt->execute(array($id)); $data=$stmt->fetchall(pdo::fetch_column); ... } ... ?> to eliminate duplicated code, wish execute query in function.
how benefit improved performance of prepared statement under scenario?
note the following code provides no efficiency benefits, , slower not using prepared statements in first place.
<?php function getstuff($x) { ... $stmt=$conn->prepare('select mytable x=?'); $stmt->execute(array($x)); $data=$stmt->fetchall(pdo::fetch_column); ... return $data; }; ... foreach($array $x){ $data=getstuff($x); ... } ... ?>
i have used in past:
function getstuff($x) { global $conn; static $stmt; if (null === $stmt) { $stmt = $conn->prepare('select mytable x=?'); } this works if function stateless. instance, not make sense make $conn variable argument:
function getstuff($conn, $x) { static $stmt; if (null === $stmt) { $stmt = $conn->prepare('select mytable x=?'); } because, static statement won't belong supplied connection.
however it, need make statement persist either within function, or otherwise use function factory , cache statement elsewhere.
edit, testing non-oop scenario:
echo '<pre>'; function do_something() { static $i = 0; echo $i . php_eol; $i++; } do_something(); do_something(); do_something(); do_something(); do_something(); output:
0 1 2 3 4
Comments
Post a Comment