2

I am fairly new to SQL-Server and PHP, but I'm trying to get the total number of rows in my table with PHP.

This is the code I am using, it connects just fine, however it won't print the number of rows:

<?php
$serverName = "SERVER1\SQLEXPRESS";
$connectionInfo = array( "Database"=>"petitionlist");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
     ?>
        <b>Error: </b>Could not connect to the server database.
     <?php
     die( print_r( sqlsrv_errors(), true));
}
$tsql = "Select Count(*) from SignatureTable";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false )
{
     ?>
     <b>Error: </b>
     <?php
     die( print_r( sqlsrv_errors(), true));
}
    ?>
    <b>Result:</b><br />
    <?php
print_r(sqlsrv_fetch_object($stmt));

sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>

If I execute the "Select Count(*) from SignatureTable" command on the SQL Server Studio it returns the correct number. So It's not my server, it's my code.

1
  • What does that code print? What happens if you give that result field an alias (which is definitely a good idea to make addressing that field easier)? Commented Sep 9, 2012 at 6:16

2 Answers 2

3

I believe that your call to

print_r(sqlsrv_fetch_object($stmt));

might be wrong. At least looking at the documentation in regards to how the call is made, indicates that there might be an error there.

http://www.php.net/manual/en/function.sqlsrv-fetch-object.php

You might want to try using fetch instead of fetch-object. I would suggest following the example.

http://www.php.net/manual/en/function.sqlsrv-fetch.php

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

Comments

2

Check it:

http://www.php.net/manual/es/function.sqlsrv-num-rows.php

"sqlsrv_num_rows() — Retrieves the number of rows in a result set"

Like:

$row_count = sqlsrv_num_rows( $stmt);
echo 'numRows: ',$row_count;

1 Comment

Are you really suggesting to do a SELECT * just to see the row count?

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.