douzhao1912 2013-10-14 14:01
浏览 53
已采纳

PDO和MySql只输出一行一行

When selecting and displaying records using php's PDO and MySql, how can I print one row once and loop through the rest? In the code below, I need to print $row['parentName'] only once, and loop through all the other row. What is an efficient way to do it? The way I'm doing it does not work and I get Notice: Undefined variable: row in C:\web\apache\htdocs\index.php on line 227.

I don't mind taking a whole new approach, since this isn't implemented yet.

$stmt = $conn->prepare($sql);
$stmt->execute($thisArray);
    $rows = $stmt->rowCount();
        if($rows >= 1) {
            echo '<div>'.$row['parentName'].'</div>'; //Echo only once.
            while($row = $stmt->fetch()) {
                echo '<div>'.$row['childName'].'</div>';
            }
        } else {
            echo 'We could not find anything to display.';
        }

EDIT I'm stuck at the fetch part.

  • 写回答

1条回答 默认 最新

  • dtz8044 2013-10-14 14:56
    关注

    Try this:

    $stmt = $conn->prepare($sql);
    $stmt->execute($thisArray);
    if ($stmt->rowCount() >= 1) {
        $array = $stmt->fetchAll();
        echo '<div>', $array[0]['parentName'], '</div>';
        foreach ($array as $row) {
            echo '<div>', $row['childName'], '</div>';
        }
    } else {
        echo 'We could not find anything to display.';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件