如何在PHP应用程序中打印mysql中的行号

时间:2016-12-28 03:18:47

标签: php mysql row-number

我有一个mysql表需要在前端应用程序中显示数据和行号。以下查询在phpMyadmin

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

但是当我在php项目中使用相同的代码时,它返回以下错误     警告:mysql_fetch_array():提供的参数不是有效的MySQL

以下是我的代码:

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

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

您的查询无效,因为您在mysql_query中设置了2个不受支持的查询。而是使用mysqli_multi_query()函数。

无论如何,mysql_*函数已被弃用,因此请改用mysqli_*函数。

$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

答案 2 :(得分:0)

我看了一下,认为你是试图制作复杂的,请看下面的代码,它很容易达到你的目的

<?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++
}
?>

答案 3 :(得分:0)

在这里,我为您提供解决方案,如何使用PHP和MYSQL获得总行数。请参见下面的代码。

    <?php
           $pdoconnection = 
          "mysql:host=localhost;dbname=database_name;charset=utf8mb4";
           $options = [
          PDO::ATTR_EMULATE_PREPARES => false,
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
         PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
      ];
   try {
        $pdo = new PDO($pdoconnection, "userName", "passWord", $options);
        $emp=$pdo->prepare("SELECT count(*) FROM emp_tab");
        $emp->execute();
        $emprow = $emp->fetch(PDO::FETCH_NUM);
      //total count
       $empcount = $emprow[0];
       } catch (Exception $e) {
          error_log($e->getMessage());
             exit('oops ! some problems');
          }
 ?>

我希望,您将对在php和mysql中使用总行数有所了解。