Billy Bones
Billy Bones

Reputation: 2965

Sending Current Variable Value through a Link

I have a table that is generated from data inside of a database. Each row of the table is one row of my database. At the end of each row I create a link to start the process of removing the data from the table and database. Here is a snip of my code:

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<th>".$row["username"]."</th>";
        $user = $row["username"];
        echo "<th>".$row["name"]."</th>";
        $name = $row["name"];
        echo "<th><a href='./test.php'.urlencode($user)>Remove</a></th>";
        echo "</tr>";
    }
}

As you can see, once the link is clicked I want to run test.php with the variable (and its value for that row) already set. Ive attempted to do this with urlencode but when doing a echo $user, it returns as undefined variable. I have also tried echo "<th><a href='./test.php?link='$user>Remove</a></th>";. I would like to be able to send up to 6 variables with values.

EDIT 1: Here is a picture of one row from my table: enter image description here

The first two columns are username and name. You can see that the values are set and displayed within the while loop. I would like each iteration of the loop to create a unique link to remove that row from the database. Or simply for this case, send the data values for that row when the link is clicked.

Upvotes: 0

Views: 78

Answers (2)

Cosmin Staicu
Cosmin Staicu

Reputation: 1947

You are not defining the variable name in your link. The line

echo "<th><a href='./test.php'.urldecode($user)>Remove</a></th>";

should look like

echo "<th><a href='./test.php?user=".urlencode($user)."&name=".urlencode($name)."'>Remove</a></th>";

then, in your test.php file you will read those variables with $_GET['user'] and $_GET['name'].

Also, beware that in your original code, you are using urldecode instead of urlencode

Upvotes: 0

Dharman
Dharman

Reputation: 33247

You can use http_build_query function:

$qs = [
    'user' => $row["username"],
    'name' => $row["name"],
    // ... 4 more values
];
echo '<th><a href="test.php?' . http_build_query($qs, null, '&amp;', PHP_QUERY_RFC3986) . '">Remove</a></th>';

Upvotes: 3

Related Questions