Home  >  Q&A  >  body text

PDO usage guide: Using multiple queries to operate Sql Server

<p>I want to execute some queries that don't return a result set, and then execute a <em>real</em> query and get its results. Here's an example that doesn't work: </p> <pre class="brush:php;toolbar:false;"><?php try { $db = new PDO('dblib:host=myhost;dbname=master','user','password'); $query = "declare @entier int = 1;"; $db->exec($query); $query = "select @entier;"; $stmt = $db->query($query); $rows = $stmt->fetchAll(); print_r($rows); } catch (PDOException $e) { print ($e->getMessage()); } catch (Exception $e) { print ($e->getMessage()); } ?></pre> <p>This code doesn’t work either: </p> <pre class="brush:php;toolbar:false;">try { $db = new PDO('dblib:host=myhost;dbname=master','user','password'); $query = "declare @entier int = 1; select @entier;"; $stmt = $db->query($query); $rows = $stmt->fetchAll(); print_r($rows); } catch (PDOException $e) { print ($e->getMessage()); } catch (Exception $e) { print ($e->getMessage()); } ?></pre> <p>But this code works: </p> <pre class="brush:php;toolbar:false;"><?php try { $db = new PDO('dblib:host=myhost;dbname=master','user','password'); $query = "select 1;"; $stmt = $db->query($query); $rows = $stmt->fetchAll(); print_r($rows); } catch (PDOException $e) { print ($e->getMessage()); } catch (Exception $e) { print ($e->getMessage()); } ?></pre> <p>Thank you for your help</p>
P粉178132828P粉178132828408 days ago454

reply all(1)I'll reply

  • P粉770375450

    P粉7703754502023-08-14 16:31:58

    I know this is old, but for anyone else who finds this question via Google: You need to use PDOStatement::nextRowset to iterate over result sets from multiple queries.

    However, in some versions, there seemed to be memory issues when using nextRowset and dblib (in my case, 94Tb of memory was tried allocated...), so I ended up redesigning to avoid multiple SQL queries altogether (Instead, the value declared where it is used is copied).

    reply
    0
  • Cancelreply