0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHP 一覧表示機能、fetch+whileをfetchAll+foreachに書き換える。

Last updated at Posted at 2020-10-19

fetch+while

fetchは一件だけ取得するとそこで処理が終わる。whileでそれを繰り返すことで一覧表示できる。

while ($user = $users->fetch(PDO::FETCH_ASSOC)) : ?>
   <div class="msg">
    <img src="<?php print(htmlspecialchars($user['picture'])); ?>" />
    <p><span class="name"><?php print(htmlspecialchars($user['title'])); ?>です</span></p>
   </div>
<?php endwhile; ?>

fetchAll+foreach

fetchAllでデータを全件取得してそれを配列にまとめるので、その配列化したものをforeachで1件ずつ表示する。

$users = $users->fetchAll(PDO::FETCH_ASSOC);
  foreach ($users as $user) : ?>
   <img src="<?php print(htmlspecialchars($user['picture'])); ?>" />
   <p><span class="name"><?php print(htmlspecialchars($user['title'])); ?>です</span></p>
   <br>
<?php endforeach ?>

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?