PHP行和列计数

时间:2014-02-12 02:04:59

标签: php mysql

我想知道你们是否可以帮助我,我从一个mysql数据库中提取数据,我希望内容以行的方式回显,比如购物车。以下是我正在使用的代码。该代码运行完美,但我不知道如何向其添加行计数和列计数。

工作代码:

<?
    $dmealh = mysql_query("select count(*) from jobs_cart where mid='$mid'");
    $jmealh = mysql_fetch_array($dmealh);           
    if ($jmealh[0]) { 
        $dmealh = mysql_query("select * from jobs_cart where mid='$mid' order by date desc, time desc"); 
        while ($jmealh = mysql_fetch_array($dmealh)) {
            echo "$id - $jmealh[name] - $jmealh[meals]";
        }
    }
?>

这就是我想要数据的样子:

Row Count- Name - Meal Count
       1 - Greg - 3
       2 - Mike - 4
       3 - Tomm - 1
                  8 Meals Total

2 个答案:

答案 0 :(得分:0)

只需使用一个基本计数器来跟踪您所在的行,并在循环搜索结果时使用另一个变量来累计膳食计数,然后回显最终计数。把它全部扔进一张桌子就可以了。

<?php
$dmealh = mysql_query("select count(*) from jobs_cart where mid='$mid'");
$jmealh = mysql_fetch_array($dmealh);           
if ($jmealh[0]) { 
    $dmealh = mysql_query("select * from jobs_cart where mid='$mid' order by date desc, time desc"); 
    $total_meals = 0; // Keep track of the total number of meals. Start at zero.
    $row = 1;         // Keep track of current row. Start at one.
?>
<table>
<?php
    while ($jmealh = mysql_fetch_array($dmealh))  {
?>
    <tr>
        <td><?php echo $row; ?></td>
        <td><?php echo $jmealh['name']; ?></td>
        <td><?php echo $jmealh['meals']; ?></td>
    </tr>
<?php    
        $total_meals += $jmealh[meals];  // Add to total meals 
        $row++;                          // Increase row count
    }
?>
<tr>
    <td></td>
    <td></td>
    <td><?php echo $total_meals; ?> Meals Total</td>
</tr>    
</table>
}

答案 1 :(得分:0)

  1. 请勿使用mysql_*个功能... they're deprecated(请注意顶部附近的红色框)。
  2. $mid来自哪里?确保转义数据库输入以防止SQL injection
  3. 通过首先查询是否返回任何行,您正在做额外的工作。只需执行SELECT查询和while循环。如果没有返回任何行,则循环将不会执行。
  4. 您应该使用HTML表格来显示此数据。使用PHP变量来跟踪您的总和。
  5. 一个粗略的例子:

    $mid = mysqli_real_escape_string($mid);
    
    $rows = $total = 0;
    $result = mysqli_query("SELECT name, meals FROM jobs_cart WHERE mid = '$mid' ORDER BY date DESC, time DESC");
    echo '<table>';
    while ($row = mysqli_fetch_assoc($result)) {
        $rows++;
        $total += $row['meals'];
        echo '<tr><td>'. $rows .'</td><td>'. $row['name'] .'</td><td>'. $row['meals'] .'</td></tr>';
    }
    echo '<tr><td>&nbsp;</td><td>&nbsp;</td><td>'. $total .'</td></tr></table>';
    
相关问题