如何仅在PHP中获取第一行的特定列数据SQL? [英] How to get specific column data SQL for first row only in PHP?

查看:40
本文介绍了如何仅在PHP中获取第一行的特定列数据SQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PHP 来回显 SQL 数据库中的一些记录.这看起来很容易,但我无法理解.所以基本上,我只想获取第一行的所有列 a,b,c,d,e,其余行只获取 a,b,c.

I'm using PHP to echo out some records in SQL database. This seems easy but I can't get it. So basically, I want to get all the columns a,b,c,d,e for the first row only and just a,b,c for the rest of the rows.

$query = $assdb->prepare("Select a, b, c, d, e from Table");
$query->execute();
$stmt = $query->fetchAll(PDO::FETCH_ASSOC);

foreach($stmt as $row){
echo $row['a'] . $row['b']  . $row['c'];

//IF FIRST ROW, THEN ECHO $row['d'] and $row['e'], BUT IT DOES NOT WORK
if($row == 1){
    echo $row['d'] and $row['e']; 
  }

}//END FOREACH LOOP

我如何检查第一行?然后向其中添加特定数据?

HOW DO I CHECK FOR FIRST ROW? AND THEN ADD SPECIFIC DATA TO IT?

推荐答案

Use simple flag $is_first:

Use simple flag $is_first:

$is_first = true;
foreach ($stmt as $row){
    echo $row['a'] . $row['b']  . $row['c'];

    //IF FIRST ROW, THEN ECHO $row['d'] and $row['e']
    if ($is_first) {
       echo $row['d'] . $row['e']; 
       $is_first = false;
    }
} //END FOREACH LOOP

否则你可以使用 foreach 之类的

Else you can use foreach like

foreach ($stmt as $key => $row) {
    echo $row['a'] . $row['b']  . $row['c'];
    if ($key == 0) {
        echo $row['d'] . $row['e']; 
    }
}

如果您 $stmt 是零索引数组,请检查是否 $key == 0.

and if you $stmt is zero-indexed array check if $key == 0.

这篇关于如何仅在PHP中获取第一行的特定列数据SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆