Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 841
Saberdream Avatar asked Jan 09 '14 15:01

Saberdream


People also ask

What will unbuffered database query do?

Unbuffered MySQL queries execute the query and then return a resource that points to the result set. This uses less memory, and allows MySQL to continue executing the query as the result set is used. It also increases load on the server.

Can I use PDO and MySQLi together?

Yes, it is possible.

What is unbuffered query in PHP?

Unbuffered queries can also be referred to as "use result". Following these characteristics buffered queries should be used in cases where you expect only a limited result set or need to know the amount of returned rows before reading all rows. Unbuffered mode should be used when you expect larger results.

Is PDO more secure than MySQLi?

PDO is more secure than the first two options and it is also faster in comparison with MySQLi procedural and MySQLi object-oriented. PDO is a database access layer that provides a fast and consistent interface for accessing and managing databases in PHP applications.


1 Answers

Re, this doesn't work, I obtain an error while using your method:

SQLSTATE[IM001]: Driver does not support this function: This driver doesn't support setting attributes

What's wrong?

Edit : I found the solution on php.net doc.

If you use this:

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

It doesn't work.

But if you set it in an array in prepare(), it works fine.

$sth = $pdo->prepare('SELECT * FROM my_table',
array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));

I hope this will help people who haven't found a way for this problem.

like image 51
Saberdream Avatar answered Oct 02 '22 08:10

Saberdream