【发布时间】:2021-03-25 13:20:33
【问题描述】:
我几乎已经使用 PHP OOP 创建了一个完整的动态页面。我已经成功创建了一个工作菜单——即当单击菜单项时,页面上会显示相关文本。但是,我想要的是默认显示主页文本,而不是单独单击主页链接。
这是我正在使用的代码:
<?php
include_once('includes/connection.php');
include_once('includes/Article.php');
//instanstiating the article class and ssigning it to a variable
$article = new Article;
//assigning the contents of the method called fetch_all to the variable $articles
//this fetch_all method is inside the Articles class which is assigned to the above variable $article
$articles = $article->fetch_all();
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple PDO CMS</title>
<link rel="stylesheet" type="text/css" href="assets/styles.css">
</head>
<body>
<div class="container">
<table class="topMenu">
<tr>
<td>
<h1 class="siteName">site name</h1>
</td>
<!--Displaying the articles using a foreach loop-->
<?php foreach ($articles as $article){ ?>
<td class="navItem">
<a href="index.php?id=<?php echo $article['id']; ?>"><?php echo $article['menuheader']; ?></a>
</td>
<?php } ;?>
</tr>
</table>
</div>
<p> this is where the time line will go</p>
<?php
//instanstiating the article class and ssigning it to a variable
$newArticle = new Article;
//checking if the user clicked the menu link
if (isset($_GET['id'])) {
//the display the article content
$id=$_GET['id'];
$data=$newArticle->fetch_data($id);
?>
<p><?php echo $data['bodytext']; ?></p>
<?php
} else {
}
?>
<p>This is where the footer will go</p>
</body>
</html>
到目前为止我已经尝试过:$id = 1;并使用重定向到 index.php。两者都不起作用,后者是由于“重定向很多”。
我想保留我目前使用的代码,而不是再次重做,所以如果你能提供帮助,请给我关于这段代码的建议。
谢谢
【问题讨论】:
-
为什么此时需要重定向?如果未设置
$_GET['id'],则设置$id = 1;,然后按照相同的方式进行操作,如果该值首先是从外部传入的…… -
$data=$newArticle->fetch_data($id);应该在if之外。在任何情况下,您都希望获取数据,而不是仅如果设置了$_GET['id']。