3

I'm using something like the following PHP code to put all data from a query into an array:

<?php

$results = array();

$q = odbc_exec("SELECT * FROM table");

while ($row = odbc_fetch_array($q)) {
    $results[] = $row;
}

?>

This works fine, but it is very slow when the query contains thousands of rows.

My question is, is there any way in PHP to dump all the data into an array without having to loop through each record one by one?

NOTE: Using MS SQL Server for the database.

3
  • When you have to read a lot of data, it will always need some time. Do you really need ever single row of that table? What are you trying to do? Commented Feb 7, 2013 at 15:29
  • You can do stuff inside the while loop itself, if you don't need to rely on the array any further. Commented Feb 7, 2013 at 15:29
  • I was hoping there was a function to put the entire query contents into an array with out using the while loop. Commented Feb 7, 2013 at 15:34

3 Answers 3

1

You could try using mssql functions instead of odbc, but its unlikely to make a large difference.

With the way drivers work, the result set is an iterator handle to the result data itself. In some cases, php doesn't actually get the data until the row is requested by php. Unless there is a fetch all available in the driver, looping through all the rows is generally your only option.

If you don't need all the columns, you could limit the data being transfered by specifing only the columns you actually need.

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

Comments

1

Specifying the cursor_type in odbc_connect made odbc fetching much quicker.

$conn = odbc_connect($dsn, $user, $pass, SQL_CUR_USE_ODBC)

http://aaronsaray.com/blog/2007/08/02/odbc-for-udb-and-php-how-i-increased-performance-by-400/

Comments

0

I was able to find a way to do this with ADOdb (a database abstraction library for PHP) using the GetAll() function:

http://adodb.sourceforge.net/

$results = $DB->GetAll("SELECT * FROM table");

This returns all the rows as a 2-dimensional array.

2 Comments

According to their website...Installing the ADOdb C extension will speed up GetAll() and GetArray() by 100% (adodb.sourceforge.net/#extension). Without using the C extension it seemed just slightly quicker then standard PHP code.
It might be that even with the extension, you wouldn't notice much difference. Dunno. Would be interesting to find out if there is any noticable benefit - I'm a bit skeptical that there would be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.