PHP Doku:: Ergibt die Zeilenzahl des Abfrageergebnisses - function.odbc-num-rows.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzDatenbankerweiterungenAbstraktionsebenenODBC (Unified)ODBC Funktionenodbc_num_rows

Ein Service von Reinhard Neidl - Webprogrammierung.

ODBC Funktionen

<<odbc_num_fields

odbc_pconnect>>

odbc_num_rows

(PHP 4, PHP 5)

odbc_num_rows Ergibt die Zeilenzahl des Abfrageergebnisses

Beschreibung

int odbc_num_rows ( int $result_id )

odbc_num_rows() liefert die Anzahl Zeilen eines ODBC-Abfrageergebnisses. Tritt ein Fehler auf, ist sie -1. Bei INSERT, UPDATE und DELETE-Befehlen wird die Zahl der betroffenen Zeilen zurückgegeben. Bei einer SELECT-Abfrage kann dies die Anzahl der vorhanden Zeilen sein.

Hinweis:

Bei vielen Treibern wird -1 als Anzahl möglicher Zeilen nach einem SELECT-Befehl zurückgeliefert.


38 BenutzerBeiträge:
- Beiträge aktualisieren...
Vadim Istratov
12.11.2010 17:35
There is a much better way to count rows in SELECT queries for MSSQL. Just use T-SQL.

Thus the function would be:
<?php
function odbc_mssql_num_rows($dbh) {
   
$res = odbc_exec($dbh, 'SELECT @@ROWCOUNT AS cnt');

    if ( @
odbc_fetch_into($res, $row)) {
       
$count = trim( $row[0] );
    } else {
       
$count = 0;
    }
   
   
odbc_free_result($res);
    return
$count;
}
?>

Where $dbh is your database connection resource (see odbc_connect()). And make sure that your SELECT statement is a last query before your odbc_mssql_num_rows() call.
walt at brookhouse dot co dot uk
9.07.2010 23:45
The easy way to count the rows in an odbc resultset where the driver returns -1 is to let SQL do the work:

<?php

    $conn
= odbc_connect("dsn", "", "");
   
$rs = odbc_exec($conn, "SELECT Count(*) AS counter FROM tablename WHERE fieldname='" . $value . "'");
   
$arr = odbc_fetch_array($rs);
    echo
$arr['counter'];

?>
chew_baka at hotmail dot com
18.05.2010 23:44
None of these examples were working for me, so I came up with the following silly procedure that gives me the number of rows.  This example is crude, but you should get the idea.

<?php
$cxn
= odbc_connect("ODBC_DSN_NAME", "", "");
$sql = "SELECT * FROM some_table'";
$res = odbc_exec($cxn, $sql);
$items = 0;
 while (
$row = odbc_fetch_array($res))
   {
      
$items++;                          
   } 
 
odbc_free_result($res);
  echo
"<br>total No. of rows: $items";
?>
jeff at script-xs dot com
2.01.2009 20:34
After minutes of frustration, I realized why odbc_num_rows was not returning the number of affected rows on a prepared update query.  I'm using ODBC to connect to Microsot SQL Server 2005.

My corrected code:

<?php
$query
= odbc_prepare($conn, 'UPDATE table SET cat = ? WHERE id = 1');
$result = odbc_execute($query, $category);
$affected = odbc_num_rows($query);
?>

This code works.  I was frustrated that odbc_num_rows($result) didn't work as I expected, but instead required me to pass the original prepared query to this function.
sirio3mil at gmail dot com
17.06.2008 18:46
The diference between functions used here are consierable, for example for one table with 36 columns and 806 rows the time to execute two of those functions are this:

function using odbc odbc_result_all take 2,6 seconds
function using odbc_fetch_row take 0,8 seconds
areznik at survdata dot com
30.11.2007 19:04
I could have been noted before in this thread but I couldnt find it on my first search.

This function (odbc_num_rows) returns -1 when ODBCing to MS SQL and making it hard to get the number of rows in the returned recordset.

Two workarounds:
   1. When you just need to verify that any rows returned from your query you can use select count(*) as cnt from table and then just get $row['cnt']
   2. When you need to actually loop through the records this function returns number of rows in the recordset if and only if you include ORDER BY clause in your query statement.

That sounds a bit annoying but thats the work around when dealing with MS SQL odbc driver I guess.

It would be beneficial if someone explained how the Order By clause makes the difference.
Nathaniel at comtel dot com dot au
31.10.2007 5:57
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.
pmo@raadvst-consetatDOTbe
16.10.2007 11:46
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).
nielsvandenberge at hotm dot dot dot dot dot com
11.09.2007 14:06
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).
voland at digitalshop dot ru
26.03.2007 17:50
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;

}
voland at digitalshop dot ru
5.03.2007 14:56
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;
}
dm at personalcomputingsolutions dot co dot uk
7.02.2007 22:41
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
}
lechatthierry at hotmail dot com
10.08.2006 19:29
<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.
patx00 put_an_at_symbol_here gmail.com
7.04.2006 9:28
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.
michael dot buergi at gmx dot net
5.04.2006 14:14
Look at the notes for odbc_fetch_row to find a custom num_rows() function which implements a binary search algorithm.
ramon
27.08.2005 10:41
odbc_num_rows for access does return -1. I use count($resultset);
 it seams to work.
moogleii
19.08.2005 18:21
With MS SQL, I found if you add an ORDER BY to your SELECT statement, the function will return the correct number of rows.
Alain
9.08.2005 20:22
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.
tysonswing at hotmail dot com
26.03.2005 9:08
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
ashley at ashley-young dot com
29.11.2004 19:57
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.
paul at mNoOvSePtAoMiNcOeSlPaMnNdO dot ScPoAmM
30.09.2004 20:25
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.
Lambert Antonio [ lamy ]
8.12.2003 18:30
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
Saran
25.09.2003 9:16
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...
avodiez at hotmail dot com
16.09.2003 21:36
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
-/-/- Jag Alskar Carla och Sverige -/-/-
24.04.2003 21:08
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_
10.04.2003 23:50
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_
EC
27.03.2003 21:55
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 at yahoo dot NOSPAM dot com
17.12.2002 0:51
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).
webmaster at walia dot com
23.11.2002 16:09
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.
fergus at serif dot net
23.10.2002 17:21
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.
Christian dot Schlager at t-online dot de
14.10.2002 14:21
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.
masuod_a at hotmail dot com
22.02.2002 21:34
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;
}
oscaralvaro at correo dot udep dot edu dot pe
28.01.2002 3:27
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.
mikeheald at streamgroup dot SPAMBGONE dot co dot uk
28.11.2001 20:14
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 at uwaterloo dot ca
2.10.2001 21:47
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
nlange at NOSPAM dot usb dot com
18.07.2001 1:44
Quick note on buggy odbc drivers...<BR>
For the Tandem ODBC Driver <BR> odbc_num_rows() returns -1 up until the very last row fetched <BR>[for example, while(odbc_fetch_into()){} ]...<BR><BR> So, you can at least tell which is the last row using odbc_num_rows(), which proves useful in HTML rendering situations...
ntp at panda dot bg dot unv dot gda dot pl
22.03.2001 16:31
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)
shinelight at excite dot com
14.02.2001 6:23
A better method for calculating the record count (without being forced to use objects) is:

<?php
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).



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)