0

How can I fetch multiple rows at once from a MySQL table in PHP?

Suppose my query returns 5 rows in all and I specify a block size of 2, the function must return an object/array with 2+2+1 rows successively.

P.S. I know that I can iterate over all the results manually and do the same implementation myself, but I am looking for some built-in function that does this cleanly and in an optimized way.

6
  • 2
    What is your db driver: MySQLi, PDO? Commented Nov 28, 2012 at 17:12
  • I am not exactly sure. I use the built in PHP function mysql_fetch_row to do this. What driver is this? Commented Nov 28, 2012 at 17:16
  • 1
    @Gowtham That's a function belonging to the mysql extension. Those functions are no longer recommended. Commented Nov 28, 2012 at 17:18
  • I just read that these functions are deprecated. Is there a way to do this using any other driver? Commented Nov 28, 2012 at 17:21
  • 2
    Please don't use the mysql_* functions as they are in the deprecation process. Use MySQLi or PDO instead and be a better PHP Developer. Commented Nov 28, 2012 at 17:25

2 Answers 2

1

Look into using the PDO object if you're not already using it. That way, you'll be able to make use of the fetchAll function.

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

Fetch all of the remaining rows in the result set:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [0] => pear
            [COLOUR] => green
            [1] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [0] => watermelon
            [COLOUR] => pink
            [1] => pink
        )

)
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for providing code, but this does not solve my problem. It fetches all the rows at once and I have to iterate over them again individually. I want a bunch of rows to be fetched at once.
0

The function you're looking for does not exist. Write it yourself.

1 Comment

I have to accept this as the right answer. Will change it if anyone comes up with something better.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.