Search code examples
phpselectmysqlihref

Repeat link with $_GET


Fairly new and inexperienced with PHP, and I'm stuck.

I have a feature that creates a new sub page that is related to a main page, eg. main page 1 has sub page 1 a, 1b and 1c, and main page 2 has sub page 2a, 2b, 2c and so forth. You gain access to the given sub pages through links in a menu on each of the main pages. I hope you're still with me here.

I have succeeded in getting the menu to link to one of the created sub pages, but what I now need is to get a link dynamically created in the menu whenever I create a new sub page. Main pages and their "id" is connected to the related sub pages via the column "mainid" that corresponds to eachother (eg. index.php?id=5&mainid=5)

The link menu is created by using $_GET.

I have this page: localhost/site/index.php?id=1&mainid=1 with the following code that i'm struggling with:

<table width="90%" border="0" cellpadding="5"><tbody>
<tr>
  <td>
  <?php 

  $id = $mysqli->query("SELECT id FROM page_content WHERE mainid =" . $_GET['mainid'])->fetch_object()->id; 
  $name = $mysqli->query("SELECT name FROM page_content WHERE mainid =" . $_GET['mainid'])->fetch_object()->name;


  ?>

  <a href="index.php?id=<?php echo $id; ?>&mainid=<?php echo $_GET['mainid']; ?>">

  <?php

print $name;

?></a></td>
  <td>&nbsp;</td>
</tr>

This creates a link to content of the sub page. The content of this sub page is stored in id=10 and mainid=5 (thus creating the link index.php?id=10&mainid=5

So far so good.

But how do I get links to be dynamically created on a main page whenever I create a new sub page belonging to that given main page?

Help is much appreciated

Thanks


Solution

  • I'm not sure what you are tying to do, but i guess you want to make a loop from database.

    To do that, you have to modify your code because right now is not safe, and not good.

    use this one instead:

    <table width="90%" border="0" cellpadding="5"><tbody>
    <tr>
      <?php
      /* create a prepared statement */
      $query = $mysqli->prepare("SELECT id,name FROM page_content WHERE mainid = ?");
      /* bind parameters  */
      $query->bind_param("i", $_GET['mainid']);
      $query->execute();
    
      $menu_result = $query->get_result();
    
      /* now you can fetch the results into an array */
      while ($menu = $menu_result->fetch_assoc()) {
    echo <<<HTML
    <td>
        <a href="index.php?id={$menu['id']}&mainid={$_GET['mainid']}">{$menu['name']}</a>
    </td>
    <td>&nbsp;</td>
    HTML;
      }
    
       ?>
    
    </tr>
    
       </tbody>
        </table>