obiwanconobi
obiwanconobi

Reputation: 35

Creating a dynamic hyperlink with php

I'm pretty new at PHP and I'm working on a task and I need to link to another page, however, I need to pass a variable through to that next page, but the variable will come from which link they clicked.

For instance, there will be multiple links on the same page and when they are clicked they will hopefully take someone to another page which loads data from a mysql db based on which link they clicked.

echo '<div class="outereventdiv"><a href="http://example.com"> <div class="eventdiv"><div class="eventimagediv">' . $imgpath . '</div><div class="eventnamediv"><p>' . $ac . "</p></div>" . '<div class="eventdatediv"><p>' . $bc .  "</p></div></div></a></div>";

That part of code creates the link, which is a clickable div essentially, which 3 parts of information.

I know I can use global variables to pass the data, but how would I store the information from which link they clicked into a global variable?

Not sure that I have worded this the best, but any help would be very much appreciated!

Upvotes: 0

Views: 1121

Answers (1)

CherryDT
CherryDT

Reputation: 29011

You can encode it in a query parameter in the URL. You can access query parameters using the $_GET superglobal.

Example:

page.html

<a href="test.php?linkId=A">Link A</a>
<a href="test.php?linkId=B">Link B</a>

test.php

You came from link <?php echo htmlentities($_GET['linkId']); ?>!

In case you dynamically create the link, don't forget to encode the value - as URI parameter and with HTML entities:

<?php
  $linkId = "Some <value> here!";
?>
<a href="test.php?linkId=<?php echo htmlentities(urlencode($linkId)); ?>">Link</a>

Upvotes: 2

Related Questions