Search code examples
phphtmlget

How do I send a variable via GET Request between 2 php pages


In my program, I have a table Artists in my database with an ID, name, and gender. I am trying to create 2 PHP pages.

  • The first page prints the name of all artists and their genders.
  • I want to hyperlink every name on the first page, to the second page. So whenever I click the artist, the ID is sent to the second page.
  • I will use the ID to compare to another table to print out some other information.

I am trying to perform the above procedure using GET. However, my code isn't working. The value I am trying to send is row[artist_id] ie, $id.

First PHP Page ......

$sql = 'SELECT name, gender,artist_id FROM artists '
                 . ' ORDER BY name ASC, artist_id ASC';
          $result = $pdo->query($sql);
          echo "<table>";
          echo "<tr><th>Artist name</th><th>Gender</th></tr>";
          foreach ($result as $row) {
             echo "<tr>";
             $name = htmlspecialchars($row['name']);
             $gender = htmlspecialchars($row['gender']);
             $id = $row['artist_id'];
             echo "<td><a href='artist_events.php'?val=$id>".$name."</a></td>";
             echo"<td>".$gender."</td>";
             echo "</tr>";

Second PHP Page

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
<style>
table,th,td{
border: 1px solid black;
}
</style>
    <title>My second PHP page</title>
  </head>
  <body>
    <?php
      include 'config.php';
    ?>
    <?php
    $my_id= $_GET['val'];
    echo $my_id;

    ?>

</body>

Solution

  • echo "<td><a href='artist_events.php'?val=$id>".$name."</a></td>";
    

    The issue is with this line. You have closed the href attribute before passing the GET parameter.

    Change it to

    echo "<td><a href='artist_events.php?val=$id'>".$name."</a></td>";
    

    I have changed the position of closing quotes for href attribute.