简体   繁体   English

如何仅在PHP中获取第一行的特定列数据SQL?

[英]How to get specific column data SQL for first row only in PHP?

I'm using PHP to echo out some records in SQL database. 我正在使用PHP回显SQL数据库中的某些记录。 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. 因此,基本上,我只想为第一行获取所有列a,b,c,d,e,而为其余各行获取仅a,b,c。

$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 : 使用简单标志$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

Else you can use foreach like 否则你可以像这样使用foreach

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

and if you $stmt is zero-indexed array check if $key == 0 . 如果$stmt是零索引数组,则检查$key == 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM