Note that there are some explanatory texts on larger screens.

plurals
  1. PORecursion in prepared statements
    primarykey
    data
    text
    <p>I've been using PDO and preparing all my statements primarily for security reasons. However, I have a part of my code that <em>does</em> execute the same statement many times with different parameters, and I thought this would be where the prepared statements really shine. But they actually break the code...</p> <p>The basic logic of the code is this.</p> <pre><code>function someFunction($something) { global $pdo; $array = array(); static $handle = null; if (!$handle) { $handle = $pdo-&gt;prepare("A STATEMENT WITH :a_param"); } $handle-&gt;bindValue(":a_param", $something); if ($handle-&gt;execute()) { while ($row = $handle-&gt;fetch()) { $array[] = someFunction($row['blah']); } } return $array; } </code></pre> <p>It looked fine to me, but it was missing out a lot of rows. Eventually I realised that the statement handle was being changed (executed with different param), which means the call to fetch in the while loop will only ever work once, then the function calls itself again, and the result set is changed.</p> <p>So I am wondering what's the best way of using PDO prepared statements in a recursive way.</p> <p>One way could be to use fetchAll(), but it says in the manual that has a substantial overhead. The whole point of this is to make it more efficient.</p> <p>The other thing I could do is not reuse a static handle, and instead make a new one every time. I believe that since the query string is the same, internally the MySQL driver will be using a prepared statement anyway, so there is just the small overhead of creating a new handle on each recursive call. Personally I think that defeats the point.</p> <p>Or is there some way of rewriting this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload