Home » Php » php – Not getting anything back from sqlsrv_num_rows

php – Not getting anything back from sqlsrv_num_rows

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m trying pull back data from MS SQL via a php page. I have got a valid connection, and am trying a simple SELECT * FROM MyTable but sqlsrv_num_rows is just blank no matter what I do!!!

Here is my code:

    function connect() {

    $serverName = DB_HOST; //serverName\instanceName
    $connectionInfo = array( "Database"=>DB_NAME, "UID"=>DB_USER, "PWD"=>DB_PASSWORD);
    $this->connection = sqlsrv_connect( $serverName, $connectionInfo);
    sqlsrv_connect( $serverName, $connectionInfo);


    if( $this->connection ) {
         echo "<br>Connection established.<br />";
    }else{
         echo "<br>Connection could not be established.<br />";
         die( print_r( sqlsrv_errors(), true));
    }       


}

The echo for Connection established is working so all AOK there!

Now when I do a simple query:

    function query($sql) {
    if ($this->debug) {
        echo $sql . "<br />";
    }       
    $this->sql = $sql;
    $this->recordset = sqlsrv_query($this->connection, $sql);

    if (!$this->recordset) {
        die('<br><br>Invalid query :<br><br><bold>' . $this->sql . '</bold><br><br>' . sqlsrv_errors());
    }

    echo "<br>rows = " . sqlsrv_num_rows($this->recordset);

I get absolutely nothing from the above echo? Any reason why? Or can you suggest a new echo I can try to debug this?

All my code in my DB class is converted from mysql so there may be a few bits wrong that is doing the damage!

I’ve even tried a super simple version, all the code together and it’s still blank/false:

    $server = DB_HOST;
$conn = sqlsrv_connect( $server, array( "Database"=>DB_NAME, "UID"=>DB_USER, "PWD"=>DB_PASSWORD) );
$stmt = sqlsrv_query( $conn, "SELECT * FROM MyTable");
$row_count = sqlsrv_num_rows($stmt);
echo "<br>row count = " . $row_count;
if ($row_count === false)
  echo "\nerror\n";
else if ($row_count >=0)
  echo "\n$row_count\n";
  die;
How to&Answers:

Try this…..

Replace below statement

sqlsrv_query( $conn, "SELECT * FROM MyTable");

as

sqlsrv_query( $conn, "SELECT * FROM MyTable", array(), array("Scrollable"=>"buffered"));