前提・実現したいこと
phpMyAdminを使い、PHPでECサイトを作成しています。
発生している問題・エラーメッセージ
while文でデータベースにある情報をそれぞれ表示したいのですが、同じ情報が複数表示されてしまいます。
該当のソースコード
index
1<?php 2require_once('data.php'); 3 4?> 5<!DOCTYPE html> 6 7<html lang="ja"> 8 <head> 9 <meta charset="utf-8"> 10 <title>*******</title> 11 <link rel="stylesheet" type="text/css" href="style.css"> 12 </head> 13 <body> 14 15 <div class="item-list"> 16 <?php foreach ($items as $item): ?> 17 <div class="item"> 18 <h3 class="item-name"><?php echo $item->getName() ?></h3> 19 <p class="item-price"><?php echo $item->getPrice() ?></p> 20 <p class="item-description"><?php echo $item->getDescrption() ?></p> 21 <img src="<?php echo $item->getImage() ?> "class="item-image"> 22 </div> 23 <?php endforeach ?> 24 </div> 25 26 </body> 27 28</html> 29
data
1<?php 2require_once('item.php'); 3$host = 'localhost'; 4$dbname = '*******'; 5$dbuser = '*******'; 6$dbpassword = '**********'; 7 8try{ 9 $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8","$dbuser","$dbpassword"); 10 echo "SUCCESS"; 11}catch(PDOException $e){ 12 var_dump($e -> getMessage()); 13 die(); 14 15} 16 17try{ 18 $sql = "SELECT * FROM ********"; 19 $stmh = $pdo->prepare($sql); 20 $stmh->execute(); 21}catch(PDOException $Exception){ 22 die('接続エラー:' .$Exception->getMessage()); 23} 24 25 26 27 28 while($row = $stmh->fetch(PDO::FETCH_ASSOC)){ 29 30 $white = new Item(htmlspecialchars($row['name']), htmlspecialchars($row['price']), htmlspecialchars($row['description']), "img/whiteT.JPEG"); 31 $gray = new Item(htmlspecialchars($row['name']), htmlspecialchars($row['price']), htmlspecialchars($row['description']), "img/grayT.JPEG"); 32 33 $items = array($white, $gray); 34 var_dump($row); 35} 36 $pdo = null; 37?>
item
1<?php 2 class Item { 3 private $name; 4 private $price; 5 private $description; 6 private $image; 7 8 public function __construct($name, $price, $description, $image){ 9 $this->name = $name; 10 $this->price = $price; 11 $this->description = $description; 12 $this->image = $image; 13 } 14 public function getName(){ 15 return $this->name; 16 } 17 public function getPrice(){ 18 return $this->price; 19 } 20 public function getDescrption(){ 21 return $this->description; 22 } 23 public function getImage(){ 24 return $this->image; 25 } 26} 27 28 29 30?>
かなり詰まってしまっているのでご協力いただけると大変助かります。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2019/01/29 06:18 編集
退会済みユーザー
2019/01/29 06:32