title: Getting number of rows form SQL Server table
body: <p>I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.</p>
  
  <p>In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.</p>
  
  <p>I have this PHP code, it works but is there an other and better to get over this?</p>
  
  <pre><code>    $sql2 = "SELECT COUNT(id) FROM categories";
      $stmt2 = sqlsrv_query($conn, $sql2);
      $res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
      foreach($res as $row)
      {
          $rows = $row;
      }
  
      //if there are categories display them otherwise don't
      if ($rows &gt; 0)
      {
          $sql = "SELECT * FROM categories";
          $stmt = sqlsrv_query($conn, $sql);
  
          while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
              echo "&lt;a href='#' class='cat_links'&gt;" . $row['category_name'] . "  - &lt;font size='-1'&gt;" . $row['category_description'] . "&lt;/font&gt;&lt;/a&gt;";
          }
      }
      else
      {
          echo "&lt;p style='text-align: center'&gt;No categories yet.&lt;/p&gt;";
      }
  </code></pre>
  
  <p>I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.</p>
  
  <p>I can't use the sqlsrv_num_rows function because I then get an error, or no answer.</p>