简体   繁体   中英

How can I use a php file to display an HTML menu div in other HTML pages?

I have an index.html file, a menu.php file, and a testing.php file. I'm working on a simple web application for storing contacts into a database and (eventually) displaying them in a nicely formatted html page on my server. I'm using the WAMP stack to learn. After a lot of trial and error, I've finally got access to my database and I can insert new contacts. I want to be able to display a navigation menu at the top of every page, though, so that I can go back to the main page after adding a contact. That way I can add as many contacts as I want.

Here is the index.html file:

<!DOCTYPE html>
<html>
<body>
    <div class="menu">
    <?php include 'menu.php' ?>
    </div>
    <form action="testing.php" method="post">
        Name: <input type="text" name="name"></br>
        Phone Number: <input type='text' name="number"></br>
        <input type="submit">
    </form>
</body>
</html>

Here is the menu.php file:

<style type = "text/css"> 
.menu{
    position: absolute;
    width: 50px;
    float:right;
    height: 20px;
}
</style>
<div class = "menu">
    <?php
    echo '<a href="index.html">Home</a> -
    <a href ="/test.php">Test</a> - 
    <a href ="http:/www.google.com">Google</a>';
    ?>
</div>

Here is the testing.php file that writes to the database:

<?php
$name = $_POST["name"];
$phonenumber = $_POST["number"];
$data = array('name' => $name, 'phonenumber' => $phonenumber);

try {
    echo '<h1>Attempting connection to database.</h1>';
    $conn = new PDO('mysql:host=localhost;dbname=TestDev', "root", "pass*");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $STH = $conn -> prepare("INSERT INTO tblContacts (Name, PhoneNumber)     VALUES (:name, :phonenumber)");    
    $STH -> execute($data);

}catch(PDOException $e) {
    echo '<h1>Not connected to database.</h1>';
    $connectedBool = false;
}
?>

Why doesn't the menu show up in the pages I've included the php file in? Is there a better way to make pages and have a menu in each page? I'd appreciate any nudge in the right direction, perhaps towards a textbook or good documentation source for learning this kind of thing. The tutorials I've found so far have a similar solution but for some reason it isn't working for me.

The browser is rendering HTML because that's what you're giving it, index.html. In order for your wamp server to process the menu.php. You need to change the extension to .php on index.html. Basic HTML doesn't know what is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM