加载时想要加载 index.php

时间:2021-03-25 13:20:33

标签: php html mysqli

我几乎已经使用 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。两者都不起作用,后者是由于“多次重定向”。

我想保留迄今为止我使用过的代码,而不是再次重做,所以如果您能提供帮助,请就这段代码给我建议。

谢谢

1 个答案:

答案 0 :(得分:0)

如果 url 中没有传递任何 id,您需要做的就是将 id 设置为 1(或者您的主页是什么)。不需要 if 语句。

以下是使用 null coalescing operator 的方法:

$newArticle = new Article;

// Sets the id to what $_GET['id'] is set to if it exists, otherwise, set it to 1
$id   = $_GET['id'] ?? 1;

$data = $newArticle->fetch_data($id);
?>

<p><?php echo $data['bodytext'] ?? 'Page not found'; ?></p>

我还添加了如何在 $newArticle->fetch_data($id) 未返回任何内容的情况下显示“找不到页面”的内容。

相关问题