Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : ODBC Functions (Unified) : odbc_num_rows

odbc_num_rows

Number of rows in a result (PHP 4, PHP 5)
int odbc_num_rows ( resource result_id )

Examples ( Source code ) » odbc_num_rows

<?
$dbconn 
odbc_connect('SAMPLE''db2inst1''ibmdb2');

   
$select_stmt 'SELECT last_name FROM author';
  
$result odbc_exec($dbconn$select_stmt);
  if (
odbc_num_rows($result) > 0) {
    while (
$row odbc_fetch_array($result)) {
      
// do stuff
    
}
  }
  else {
    print 
"No results found.";
  }

?>

Code Examples / Notes » odbc_num_rows

moogleii

With MS SQL, I found if you add an ORDER BY to your SELECT statement, the function will return the correct number of rows.

pmo@raadvst-consetatdotbe

voland's function is simply great.
However, i would recommend the use of ob_end_clean(), to shut down completely the output buffer (can cause weird behaviour).


saran

Using odbc_num_rows() against MS SQL Server will return correct number of result if you add 'TOP' modifier in the select statement, make it too big number to make sure they will cover all possible records, it doesn't effect any performance, for example:
$query="select top 100000 * from employees where dept_id=$dept_id";
instead of just:
$query="select * from employees where dept_id=$dept_id";
The first statement will return the correct number of records while the latter will always return -1 if there are any records or 0 if no record at all.
However if you only want to examine whether there is a record, -1 is suffice.
Another solution is to use odbc_next_result() function, count for the records in first statement and follow by select statement, for example:
$query="select count(*)from employees where dept_id=$dept_id;select*from employees where dept_id=$dept_id"
After execute this multiple statements in a single execution, it will return multiple recordsets:
$result=odbc_exec($connection,$query);
# get number of records form count statement
if(odbc_fetch_row($result))$record_count=odbc_result($result,1);
# go to next result set
odbc_next_result($result);
# the code to handle next result set here...
Hope this help...


voland

Today we find a BEST way to count number of rows with ODBC!
function best_odbc_num_rows($r1)  {
ob_start(); // block printing table with results
(int)$number=odbc_result_all($r1);
ob_clean(); // block printing table with results
return $number;
}


ashley

To add to the note about using odbc_num_rows with the Tandem Driver:
As mentioned, the Tandem driver will return -1 until the last row. To use this to your advantage for formatting Tandem output, you can simply say:
while(odbc_num_rows($rs) == -1)
{
 $row = odbc_fetch_object($rs);
 print $row->fieldname;
}
From there, you can format Tandem output as you normally would with mssql or mysql.


ec

This is how I got odbc_num_rows to work...I was getting "-1" and "Resource id #3"  for the result until I added the variable $rows
(code)
$rows = odbc_result_all($sql_result, "border='1' bordercolor='#003636'");
odbc_num_rows($sql_result);
print "Number of rows:$rows";
odbc_free_result($sql_result);
odbc_close($connection);
?>
(code)


joef43065nospam

This function calls SQLRowCount, which according to the ODBC Specification returns "the number of rows affected by an UPDATE, INSERT, or DELETE statement;" This is not what odbc_num_rows is supposed to return, though it works with some ODBC drivers. Search for "ODBC reference sqlrowcount" (no quotes) on Google for more information (link is too long to post).

oscaralvaro

There is another SQL stament to get the rows number:
SELECT COUNT(*) from Usuario where (UsrUsername = '$username') AND (UsrPassword = '$contrasena');
I think this is more fast.


nlange

Quick note on buggy odbc drivers...
For the Tandem ODBC Driver
odbc_num_rows() returns -1 up until the very last row fetched
[for example, while(odbc_fetch_into()){} ]...
So, you can at least tell which is the last row using odbc_num_rows(), which proves useful in HTML rendering situations...


tysonswing

Quick and easy way to return the number of rows:
$query = "SELECT COUNT(*) FROM <my database name>";
$result = odbc_exec($dbc, $query);
odbc_fetch_into($result, $count, 1);
where:
$dbc = connection_id
$count =  the total number of rows


christian dot schlager

odbc_num_rows returns -1 with the drivers i'm using, too.
Using the keyword DISTINCT in the select-statement makes the function return the correct number of rows.
Alas, this doesnt work if i want to select text from a table, because in this case, you cant use DISTINCT.
Anyway, i hope it helps.


ramon

odbc_num_rows for access does return -1. I use count($resultset);
it seams to work.


nathaniel

My development computer is running XP sql2005 while the production copy sits on a server 2003R2 sql2000 computer.
In the course of trying to get this function to work (switching from mssql to odbc) I have discovered that the ODBC driver versions are different between the two OS and that while the newer version (release date 17/2/07) that is able to be installed on 2003 handles this function fine, the older version doesn't.
Microsoft sites suggest that Vista might also handle it (ie have the newer driver). It also says that there are no plans to release the newer driver in a installable package.
http://support.microsoft.com/kb/892854
Will hopefully test with the sql2005 on server 2003R2 in the near future to confirm it is the driver helping here.


michael dot buergi

Look at the notes for odbc_fetch_row to find a custom num_rows() function which implements a binary search algorithm.

lambert antonio lamy

It isnt the drivers actually that makes recordcount return -1, its because the recordcount property is a read-only property available to recordsets opened with one of two kinds of cursor types, opening it as static will return the actual value by default it is opened as forward only. FYI

patx00 put_an_at_symbol_here gmail.com

If you simply want to loop through the results of a query if there are some results a more efficient way to do it (without looping once for the count and another time for doing whatever you want to do ..) would be this:

$result2 = odbc_exec($vConn, $vSql);
if (odbc_fetch_row($result2, 1)) { //Some results
   odbc_fetch_row($result2, 0); //Go back to 1st row
   while ($vField = odbc_fetch_array($result2)) {
       ....
   }
}
I hope this helps.


webmaster

if you are using ODBC you will get -1 as the answer to this command most of the time.  I tried this on windows (sigh) and it did not work.
If you are using ODBC with a DSN for MS ACCESS then the best method would be
CODE:
--------
$connection = odbc_connect("DSN_name","userid","password") or die("ERROR");
$sql = "SELECT COUNT(*) FROM tablename";
$sql_result = odbc_prepare($connection,$sql) or die("ERROR");
odbc_execute($sql_result) or die("ERROR");
$rc = odbc_fetch_into($sql_result, $my_array);
echo ("Total rows: " . $my_array[0]);
odbc_free_result($sql_result);
odbc_close($connection);
--------
This way you do not have to go through loops and stuff. imagine if you had over 100,000 entried (rows) and you tried to count them using a loop with incrememnting counter. It would really screw up the CPU. specially if you get 100 people doing the same thing at the same time (which you never know)
Using this method is fast and most convenient for me at least.


avodiez

I've found a little mistake while trying deejay_'s function against an ODBC SQL Server driver.
If you work with that database, subqueries must be named. So if you are trying to get record number deejay_'s way, you must use AS statement when passing SELECT count(*) query as this:
where is
$countQueryString="SELECT count(*) as result FROM (".$query.")";
might be
$countQuerySrting="SELECT count(*) as result FROM (".$query.") AS anyNameYouLike ";
As well, be carefull with ORDER BY statements in subqueries as they are not accepted unless they with TOP modifyers.
Avo


masuod_a

i wrote a function for counting odbc records , this function work for all odbc drivers :
function odbc_record_count($sql_id, $CurrRow = 1)
{
if ($NumRecords=odbc_num_rows($sql_id)<0) {
$NumRecords = 0;
odbc_fetch_row($sql_id,0);
while (odbc_fetch_row($sql_id))
{
  $NumRecords++;
}
odbc_fetch_row($sql_id, $CurrRow);
}
return $NumRecords;
}


alain

I use ODBC on Windows to connect to Oracle on OpenVMS, and to execute a "select count(*)" I need to add the SQL_CUR_USE_ODBC parameter to odbc_connect.

-/-/- jag alskar carla och sverige -/-/-

I solved the problem using two "while(odbc_fetch($result))", one for counting (on top of the table) and the other to populate the table:
--- counting: ----
$result_count = odbc_exec($connection, $sql);
while (odbc_fetch_row($result_count))
{
  $count++;
}
echo "Title";
if ($count)
{
  echo "Total: <b>$count</b>.";
}
else
{
  echo "No Records Found.";
}
---- populating: ----
$result = odbc_exec($connection, $sql);
while (odbc_fetch_row($result))
{
  (...)
}
odbc_close ($connection);


deejay_

i modified the script of fergus a little bit so that you can give the whole query string to the function.
Maybe some find this one helpfull.
<?php
function odbc_record_count ($result, $odbcDbId, $query)
{
 $numRecords = odbc_num_rows ($result);
 if ($numRecords < 0)
 {
   $countQueryString = "SELECT count(*) as results FROM (".$query")";
   $count = odbc_exec ($odbcDbId, $countQueryString);
   $numRecords = odbc_result ($count, "results");
 }
 return $numRecords;
}
?>
deejay_


nielsvandenberge

I just tried to use the function best_odbc_num_rows($result) from voland at digitalshop dot ru, but it's not working quite well. After executing the function odbc_result_all(); the resultset has to be resetted again.
Resetting it with
odbc_fetch_row($result, 0);
is not working for me.
I think the internal number-value of the odbc_result_all()-function is not resetted, but that's just a guess.
when I execute the function 3 times with a resultset of 17 rows the values: 17, 34 and 51 are returned.
His previous function useful_odbc_num_rows($result) works better (for me).


mikeheald

I have found the odbc functions to be unreliable with MSSQL 7. odbc_num_rows returns incorrect results, and specifying which row to return in odbc_result has no effect (this is with php4.0.6)

t3singh

Hi, had troubles with this as well and after quite a while and after reading several posts I came up with the following:
      $to_ret = 0;
      while(odbc_fetch_row($result))
           $to_ret++;

      odbc_fetch_row($result,0);
      return $to_ret;
just put it all in a function and I think it should do


paul

Here's a quick and dirty function that *should* return the number of rows in a query even if the driver is being ornery.
<?php
function better_odbc_num_rows($con,$sql){
   $result = odbc_exec($con,$sql);
   $count=0;
   while($temp = odbc_fetch_into($result, &$counter)){
       $count++;
   }
   return $count;
}
?>
$con is your ODBC connection, and $sql is your SQL query. Put it in your header and you should be good to go.


dm

function db_get_row($cur, $rownum){
if (odbc_fetch_into($cur, $row, $rownum)){
return ($row);
}else{
return (FALSE);
}
$i=1;
if (db_get_row($cur,1)){
while ($record=db_get_row($cur,$i++)){
do stuff
}else{
tell the user there are no results
}


fergus

building on masuod_a@hotmail.com's note, above, I made this function which is similar but uses the SQL count(*) recomended in other notes. I've tested this against masuod_a's function and this is much faster for me.
function odbc_record_count($result, $conn, $db, $options) {
$numRecords=odbc_num_rows($result);
if ($numRecords<0) {
$countQueryString = "SELECT count(*) FROM $db $options";
$count = odbc_exec($conn, $countQueryString);
$numRecords = odbc_result($count, 1);
}
return $numRecords;
}
called like this: odbc_record_count($result, $conn, $dsn, "myField='myValue'");
where $result is the indicator to try first with odbc_num_rows, $conn is the result of your original odbc_connect, $dsn is the DSN used to get $conn and also works as the table name for the count(*), and $options is to add any WHERE this = 'that' SQL arguments.


ntp

An alternative way of getting the number of rows if your driver returns -1 is to requery using the above query:
SELECT Count(*) FROM (SELECT ... original query);
I don't only know which solution is faster: to requery, or to fetch lot of rows (it depends on how does SQL engine does Count operation)


voland

After a hour for a searching a good alter function of odbc_num_rows... i try to write it by mysels:
function useful_odbc_num_rows($result){
  $num_rows=0;
  while($temp = odbc_fetch_into($result, &$counter))
  {
      $num_rows++;
  }
@odbc_fetch_row($result, 0);   // reset cursor
  return $num_rows;
}


shinelight

A better method for calculating the record count (without being forced to use objects) is:
function RecordCount($sql_id, $CurrRow = 0)
{
 $NumRecords = 0;
 odbc_fetch_row($sql_id, 0);
 while (odbc_fetch_row($sql_id))
 {
   $NumRecords++;
 }
 odbc_fetch_row($sql_id, $CurrRow);
 return $NumRecords;
}
The only problem arises (in both this and the bit of code relying on objects) is when the driver does not support fetching a specific row number.  In that case, the query will have to be run again (and cross your fingers that the data has not changed in the datasource).


lechatthierry

<quote>
ramon
27-Aug-2005 04:41
odbc_num_rows for access does return -1. I use count($resultset);
it seams to work.
</quote>
I taught it was a solution once but $resultset is a ressource and count() alwais return 1 since it considered it as a single object.


Change Language


Follow Navioo On Twitter
odbc_autocommit
odbc_binmode
odbc_close_all
odbc_close
odbc_columnprivileges
odbc_columns
odbc_commit
odbc_connect
odbc_cursor
odbc_data_source
odbc_do
odbc_error
odbc_errormsg
odbc_exec
odbc_execute
odbc_fetch_array
odbc_fetch_into
odbc_fetch_object
odbc_fetch_row
odbc_field_len
odbc_field_name
odbc_field_num
odbc_field_precision
odbc_field_scale
odbc_field_type
odbc_foreignkeys
odbc_free_result
odbc_gettypeinfo
odbc_longreadlen
odbc_next_result
odbc_num_fields
odbc_num_rows
odbc_pconnect
odbc_prepare
odbc_primarykeys
odbc_procedurecolumns
odbc_procedures
odbc_result_all
odbc_result
odbc_rollback
odbc_setoption
odbc_specialcolumns
odbc_statistics
odbc_tableprivileges
odbc_tables
eXTReMe Tracker