Saberdream Saberdream - 7 months ago 20
PHP Question

Do unbuffered queries for one request with PDO

i'm looking to do unbuffered queries only on some requests.

In mysql I was doing this :

$req = mysql_unbuffered_query('SELECT * FROM forum_topics
ORDER BY (topic_id/topic_stick) DESC, topic_last_post DESC');
while($data = mysql_fetch_assoc($req)) {
// display results...
}


I looked at php doc, and according to it in
pdo
we must proceed this way to do queries unbuffered :

$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_pass');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$uresult = $pdo->query("SELECT Name FROM City");

if ($uresult) {
while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {
echo $row['Name'] . PHP_EOL;
}
}


But is it possible to do it unbuffered only for the "forum_topics" table results without setting all pdo instance to unbuffered?

Answer

if you use prepared statement (you can use them for simple select) like this:

$uresult = $pdo->prepare("SELECT Name FROM City");

then you can set attribute on uresult:

$uresult->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

then you execute the prepared statement:

$uresult->execute();
if ($uresult) {
   while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {
       echo $row['Name'] . PHP_EOL;
   }
}

then the unbuffered attribute should only be applied on your statement, instead of your whole pdo object