Search code examples
phpmysqlrow-number

How to print row number in mysql in PHP application


I have a mysql table need to display the data along with the row number in front end aplication. The following query works perfectly in phpMyadmin

SET @row_num=0; SELECT (@row_num:=@row_num+1) AS num,INV,DOS,PTNAME,BAL,PROV     from sheet;

But when i use the same code in php projects it is returning the following error Warning: mysql_fetch_array(): supplied argument is not a valid MySQL

Below is my code:

<?php 
$conn = mysql_connect("localhost","root","");
mysql_select_db("omega",$conn);
$sel="SET @row_num=0; SELECT (@row_num:=@row_num+1) AS             num,INV,DOS,PTNAME,BAL,PROV from sheet";
$sqlquery=mysql_query($sel);

while($dis=mysql_fetch_array($sqlquery))
{
echo"<tr>";
echo "<td>".$dis['num']."</td>";
echo "<td>".$dis['INV']."</td>";
echo "<td>".$dis['DOS']."</td>";
echo "<td>".$dis['PTNAME']."</td>"; 
echo "<td>".$dis['BAL']."</td>";    
echo "<td>".$dis['PROV']."</td>";       
echo"</tr>";
}

Solution

  • change from

    $sel="SET @row_num=0; SELECT (@row_num:=@row_num+1) AS num,INV,DOS,PTNAME,BAL,PROV from sheet";
    

    to

    $sel="SELECT s.*, @rownum := @rownum + 1 AS num FROM sheet s, (SELECT @rownum := 0) r";