我有问题。我想要一些数据输出我的数据库。 我在这里有两个页面的类别。我希望他能在数据库中显示所有内容。我有第二页。这是我的课程。我已经尝试了一个关于categorie.php的foreach,但是如果我这样做,那么他将数据库中的1个相同的数据显示为4次,而不是另一个数据。 您可以在下面看到我的代码。 我希望你能帮助我。
谢谢。
这是我的categorie.php
<?php
require_once '../app/functions/second.php';
require_once '../app/db/dbpassword.php';
require_once 'include/head.php';
if (isset($_GET['categorie']) && !empty($_GET['categorie'])) {
$id = $_GET['categorie'];
$dbh = new PDO("mysql:host=$host; dbname=$dbname;", $usernamedb,
$passworddb);
$cate = new Categorie($dbh);
$cate->loadCate($id);
// $page->loadId($id);
$categorie = $cate->getCategorie();
$titel = ucwords($categorie);
?>
<h2 class="center_h2"><?= $titel ?></h2>
<?php foreach ($cate as $key) {
$titelart = $cate->getTitel();
$beschrijving = $cate->getBeschrijving();
$plaatje = $cate->getImage();
$id = $cate->getId();
var_dump($titelart);
} ?>
<?php
} else {
echo "Dit bericht is verwijderd of is verplaats.";
}
require_once 'include/footer.php';
?>
这是我的课程页面
<?php
class Categorie {
protected $dbh;
public function __construct($new_dbh){
$this->dbh = $new_dbh;
}
public function loadCate($cate){
$query = $this->dbh->prepare('SELECT * FROM schilderijen WHERE categorie=?');
$query->execute(array($cate));
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
$this->id = $row->id;
$this->categorie = $row->categorie;
$this->titel = $row->titel;
$this->beschrijving = $row->beschrijving;
$this->plaatje = $row->plaatje;
}
}
public function getId(){
return $this->id;
}
public function getCategorie(){
return $this->categorie;
}
public function getTitel(){
return $this->titel;
}
public function getBeschrijving(){
return $this->beschrijving;
}
public function getImage(){
return $this->plaatje;
}
}
?>
答案 0 :(得分:0)
好的,所以你的班级使用有问题。在SQL请求之后的while
中,将值应用于$this->id = $row->id;
之类的实例变量,但此变量将使用下一行值重写。
对SQL请求使用static
函数并返回Categorie
这样的数组:
class Categorie {
protected $id, $categorie, $title, $beschrijving, $plaatje;
public function __construct($id, $categorie, $title, $beschrijving, $plaatje){
$this->id = $id;
$this->categorie = $categorie;
$this->title = $title;
$this->beschrijving = $beschrijving;
$this->plaatje = $plaatje;
}
public static function loadCate($dbh, $cate){
$query = $dbh->prepare('SELECT * FROM schilderijen WHERE categorie=?');
$query->execute(array($cate));
$res = array();
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
$res[] = new Categorie($row->id, $row->categorie, $row->titel, $row->beschrijving, $row->plaatje);
}
return $res;
}
public function getId(){
return $this->id;
}
public function getCategorie(){
return $this->categorie;
}
public function getTitle(){
return $this->title;
}
public function getBeschrijving(){
return $this->beschrijving;
}
public function getImage(){
return $this->plaatje;
}
}
你可以这样使用它:
$categories = Categorie::loadCate($dbh, $id);
foreach($categories as $categorie){
var_dump($categorie->getTitle());
}