How to print row number in mysql in PHP application

可紊 提交于 2019-12-10 19:42:23

问题


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>";
}

回答1:


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";



回答2:


Your query doesn't work because you set 2 queries in mysql_query which is not supported. Instead use mysqli_multi_query() function.

Anyway, mysql_* functions are already deprecated, so use mysqli_* functions instead.

$conn = mysqli_connect("localhost", "root", "", "omega");

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

while($dis = mysqli_fetch_array($sqlquery))
{

// rest of your code



回答3:


i took a look and think you were tried to make complex, see the code below, it's easy for your purpose

<?php 
$conn = mysql_connect("localhost","root","");
mysql_select_db("omega",$conn);
$sel="SET INV,DOS,PTNAME,BAL,PROV from sheet";
$sqlquery=mysql_query($sel);
$i=0;
while($dis=mysql_fetch_array($sqlquery))
{
echo"<tr>";
echo "<td>".$i."</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>";
$i++
}
?>


来源:https://stackoverflow.com/questions/41354929/how-to-print-row-number-in-mysql-in-php-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!