Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get The Count or The Number Of Rows In A Result Set In PHP using ODBC Connection?

While I build a web page in My PHP web application, My Connection works ok but When I want to get the count of rows of the SELECT Statement I used in my query, It gives me -1 !! although my result set has about 10 rows.

I would like to get the actual number of result set rows. I searched the PHP Manual & documentation but I do not find a direct way like a Count function or something like that.

I wonder if I have to make a Count(*) SQL Statement in another query and attach it to my Connection to get the Count of Rows ?

Does any one knows an easy and direct way to get that ?

the odbc_num_rows function always gives -1 in result so I can not get the actual number of rows.

My Programming langauge is PHP and My Database Engine is Sybase and The Way to connect to Database is ODBC.

Here are you the Code I used:-

<?PHP

//PHP Code to connect to a certain database using ODBC and getting information from it

//Determining The Database Connection Parameters
$database = 'DatabaseName';
$username = 'UserName';
$password = 'Password';

//Opening the Connection
$conn = odbc_connect($database,$username,$password);

//Checking The Connection
if (!$conn)
{
exit("Connection Failed: " . $conn);
}

//Preparing The Query
$sql = "SELECT * FROM Table1 WHERE Field1='$v_Field1'";

//Executing The Query
$rs = odbc_exec($conn,$sql);

//Checking The Result Set
if (!$rs)
{
exit("Error in SQL");
}

echo "<p align='Center'><h1>The Results</h1></p>";

while ( odbc_fetch_row($rs) )

{
  $field1 = odbc_result($rs,1);
  $field2 = odbc_result($rs,2);
  $field3 = odbc_result($rs,3);
  echo "field1 : " . $field1 ;
  echo "field2 : " . $field2 ;
  echo "field3 : " . $field3 ;
}

$RowNumber = odbc_num_rows($rs);

echo "The Number of Selected Rows = " . $RowsNumber ; 

//Closing The Connection
odbc_close($conn);

?>

Thanks for your Help :)

like image 903
TopDeveloper Avatar asked Dec 09 '22 13:12

TopDeveloper


2 Answers

odbc_num_rows seems to be reliable for INSERT, UPDATE, and DELETE queries only.

The manual says:

Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.

one way around this behaviour is to do a COUNT(*) in SQL instead. See here for an example.

like image 191
Pekka Avatar answered Jan 05 '23 18:01

Pekka


in php.net:

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'];

?>
like image 44
Ramin Rezazadeh Avatar answered Jan 05 '23 16:01

Ramin Rezazadeh