• PHP Help
  • Displaying text on page using menu links

I have a webpage that connects to a database and shows content on the index page, but I cannot work out how to have the text change when a different menu link is selected. I have Home, News, and Timeline as menu links so each has its own text.

This is what the code I have used so far:

<?php

require_once("db.php");

$pdo_statement = $dbh->prepare("SELECT * FROM pages");
$pdo_statement->execute();
$result = $pdo_statement->fetchAll();
   
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Site</title>
</head>
<body>

<?php
if(!empty($result)) { 
	foreach($result as $row) { ?>

        <a href='index.php?=<?php echo $row["pageheader"]; ?>'><?php echo $row["pageheader"]; ?></a> 
    
<?php	}
 }
?>

<p><?php echo $row["pagecontent"]; ?></p>

</body>
</html>

Thanks for any help.

steveb63 Welcome to the forums. Just a tip: wrapping your code blocks in [code]...[/code] tags works better here than using the </> button in the post editing window. I edited your post accordingly. Now I'll actually read it and see if I have any suggestions. 🙂

    If I'm understanding things correctly (not a given), it sounds like you'd want a separate query to fetch the content based on the pageheader value in the HTTP request. (You could then reduce what gets returned by the menu link query by only specifying that that pageheader column be returned.)

    Also, I'd suggest making your menu links include a "key" in the query string, so that you can grab what you need from $_GET explicitly. I'd also make the values "html safe".

    <a href='index.php?page=<?php echo urlencode($row["pageheader"]); ?>'><?php echo htmlentities($row["pageheader"]); ?></a> 
    

    In fact, after looking at that, what I'd actually do is... 😉

    printf(
        "<a href='index.php?page=%s'>%s</a>",
        urlencode($row["pageheader"]),
        htmlentities($row["pageheader"])
    );
    

    Anyway...then to display the selected page's content, you might do something like:

    $page = empty($_GET['page']) ? 'Home' : $_GET['page'];
    $content_stmt = $dbh->prepare("SELECT * FROM pages where pageheader = :page");
    $content_stmt->execute([':page' => $_GET['page']);
    // if nothing returned, maybe display a 404 Not Found page?
    // else display content retrieved by the query
    

    Thanks for the help. I will make the changes as suggested.

      Sorry to be a pain, but I get error messages:

      Connected to Database

      Notice: Undefined index: page in C:\xampp\htdocs\dynamicsite\index.php on line 7

      Notice: Undefined variable: row in C:\xampp\htdocs\dynamicsite\index.php on line 22

      Notice: Undefined variable: row in C:\xampp\htdocs\dynamicsite\index.php on line 24

      This is the code as it is now:

      <?php
      
      require_once("db.php");
      
      $page = empty($_GET['page']) ? 'Home' : $_GET['page'];
      $content_stmt = $dbh->prepare("SELECT * FROM pages where pageheader = :page");
      $content_stmt->execute([':page' => $_GET['page']]);
      // if nothing returned, maybe display a 404 Not Found page?
      // else display content retrieved by the query
      
      ?>
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Dynamic Site</title>
      </head>
      <body>
      
      <h1><a href='index.php?page=<?php echo urlencode($row["pageheader"]); ?>'><?php echo htmlentities($row["pageheader"]); ?></a></h1>
      
      <p><?php echo $row["pagecontent"]; ?></p>
      
      </body>
      </html>

      Have I missed something?

        Read the error messages. They contain information.

        1. If $_GET['page'] isn't set then you'll get an error when you try to use it on line 7, where you try to use it when setting $content_stmt.
        2. Where does $row get set? If it doesn't, then you'll get an undefined variable error message on line 22 where you try to use it.
        3. Where does $row get set? If it doesn't, then you'll get an undefined variable error message on line 24 where you try to use it.

        I'm back.

        I have done this with the suggested code:

        <?php
            require_once("db1.php");
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            
        <title>Dynamic Site</title> </head> <body> <?php $page = empty($_GET['page']) ? 'Home' : $_GET['page']; $content_stmt = $conn->prepare("SELECT * FROM pages where pageheader = :page"); $content_stmt->execute([':page' => $_GET['page']]); printf( "<a href='index.php?page=%s'>%s</a>", urlencode($row["pageheader"]), htmlentities($row["pageheader"]) ); ?> <p><?php echo $row["pagecontent"]; ?></p> </body> </html>

        I have the following error message: Fatal error: Uncaught Error: Call to a member function execute() on bool in C:\xampp\htdocs\dynamicsite\index2.php:18 Stack trace: #0 {main} thrown in C:\xampp\htdocs\dynamicsite\index2.php on line 18.

        This would be the "$content_stmt->execute([':page' => $_GET['page']]);" part.

        How do I solve this error.

          prepare will return false if the database server encounters an error when trying to prepare the statement. $conn->error ought to then contain a description of what the error was.

          Thanks for all the advice so far, but I still get errors, so I must be doing something wrong. I have edit my code using online examples, and some from advice here. This is the code I am using:

          <?php
              require_once("db1.php");
              
          $id = isset($_GET['id']) ? $_GET['id'] : ''; $pdo_statement = $conn->prepare("SELECT * FROM pages where id = $id"); $pdo_statement->execute(); $result = $pdo_statement->fetchAll(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Site</title> </head> <body> <table> <?php if(!empty($result)) { foreach($result as $row) { ?> <tr> <td><?php echo $row["pageheader"]; ?></td> </tr> <tr> <td> <a href='index1.php?id=<?php echo urlencode($row["pageheader"]); ?>'><?php echo htmlentities($row["pageheader"]); ?></a> </td> </tr> <?php } } ?> </table> <h1><?php echo $row["pageheader"]; ?></h1> <?php echo $row["pagecontent"]; ?> </body> </html>

          I assume this would work with out the error message I get, which is: Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Egypt' at line 1 in C:\xampp\htdocs\dynamicsite\index1.php:7 Stack trace: #0 C:\xampp\htdocs\dynamicsite\index1.php(7): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\dynamicsite\index1.php on line 7

          If anyone can help me achieve what I originally set out to do (dynamic url links) or can solve this issue that allows the links to work, than I would be grateful. I seem to take one step forward and two steps back.

            It looks like your query ends up being:

            SELECT * FROM pages WHERE id = Egypt

            Egypt should be in quotes. That's not a syntax error, though; you'll just get an error saying that the pages table doesn't have a column named Egypt (unless it does, of course...). So maybe you've got some wacky invisible but non-whitespace characters in there somehow.

            But you're misusing prepare/execute anyway. One of their two main purposes is to stop you from sticking random bits of user-supplied data into your queries.

            
            $id = $_GET['id'] ?? '';
            
            $pdo_statement = $conn->prepare("SELECT * FROM pages where id = :id");
            $pdo_statement->execute([':id' => $id]);
            Write a Reply...