You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP:无需SESSION/COOKIES及表单提交,传递锚点标签值至目标页面

Great question! Let's break down feasible solutions that fit your constraints—no sessions/cookies, no POST/GET form submissions, just passing the ID from an anchor link to another PHP page.

Best Solution: URL Query Parameters (GET, Non-Form Submission)

This is the simplest, most compatible approach, and it doesn't count as a "form submission" since you're just using a standard anchor link with a parameter. The ID will be appended to the target URL, but if your IDs aren't sensitive, this is perfect.

Example Implementation:

List Page (e.g., users.php)

<?php
// Assume you've already connected to your MySQL database and run a query
$result = mysqli_query($conn, "SELECT id, name FROM users");

echo "<ul>";
while ($row = mysqli_fetch_assoc($result)) {
    // Embed the ID directly in the anchor link's URL
    echo "<li>
            ID: <a href='user-details.php?id={$row['id']}'>{$row['id']}</a>
            - Name: {$row['name']}
          </li>";
}
echo "</ul>";
?>

Target Page (e.g., user-details.php)

<?php
// Retrieve the ID from the URL query string
if (isset($_GET['id'])) {
    // Sanitize the ID to prevent SQL injection
    $userId = mysqli_real_escape_string($conn, $_GET['id']);
    
    // Use the ID for further queries (example)
    $userResult = mysqli_query($conn, "SELECT * FROM users WHERE id = $userId");
    $user = mysqli_fetch_assoc($userResult);
    
    echo "<h2>Details for User {$user['name']}</h2>";
    // Display user details here
} else {
    echo "No user ID provided.";
}
?>

Why this works: It uses a standard GET request via an anchor link (not a form), avoids sessions/cookies, and is supported by all browsers and PHP versions.


Alternative 1: localStorage + JavaScript/AJAX

If you need to hide the ID from the URL (e.g., sensitive data), you can store the ID in the browser's localStorage temporarily, then pass it to the target PHP page via AJAX. This requires JavaScript support, but it keeps the ID out of the URL bar.

Example Implementation:

List Page (users.php)

<?php
$result = mysqli_query($conn, "SELECT id, name FROM users");

echo "<ul>";
while ($row = mysqli_fetch_assoc($result)) {
    // Add a data attribute for the ID and a class for JS targeting
    echo "<li>
            ID: <a href='user-details.php' class='user-link' data-id='{$row['id']}'>{$row['id']}</a>
            - Name: {$row['name']}
          </li>";
}
echo "</ul>";

// Add JavaScript to handle click events
?>
<script>
document.querySelectorAll('.user-link').forEach(link => {
    link.addEventListener('click', function(e) {
        e.preventDefault(); // Stop the default link jump
        const userId = this.dataset.id;
        // Store the ID in localStorage
        localStorage.setItem('selectedUserId', userId);
        // Manually navigate to the target page
        window.location.href = this.href;
    });
});
</script>

Target Page (user-details.php)

// First, display your page content
echo "<h2>User Details</h2>";
?>
<script>
window.addEventListener('load', function() {
    const userId = localStorage.getItem('selectedUserId');
    if (userId) {
        // Send the ID to a PHP endpoint via AJAX
        fetch('fetch-user-details.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `id=${encodeURIComponent(userId)}`
        })
        .then(response => response.json())
        .then(user => {
            // Display the user details dynamically
            document.body.innerHTML += `<p>Name: ${user.name}<br>ID: ${user.id}</p>`;
            // Clear the ID from localStorage to avoid reuse
            localStorage.removeItem('selectedUserId');
        })
        .catch(error => console.error('Error fetching user details:', error));
    }
});
</script>

PHP Endpoint (fetch-user-details.php)

<?php
header('Content-Type: application/json');
if (isset($_POST['id'])) {
    $userId = mysqli_real_escape_string($conn, $_POST['id']);
    $result = mysqli_query($conn, "SELECT id, name FROM users WHERE id = $userId");
    $user = mysqli_fetch_assoc($result);
    echo json_encode($user);
} else {
    echo json_encode(['error' => 'No ID provided']);
}
?>

Pros: ID doesn't appear in the URL. Cons: Relies on JavaScript, won't work if JS is disabled.


Alternative 2: Server-Side Temporary Storage (e.g., Redis)

For highly sensitive IDs where even localStorage isn't acceptable, you can use a server-side key-value store like Redis. Generate a unique token, map it to the ID, and pass the token in the URL instead of the raw ID.

Example Workflow:

  1. On the list page, generate a unique token (e.g., uniqid()) and store a mapping of token => user_id in Redis with a short expiration (e.g., 5 minutes).
  2. Link to the target page with the token: <a href='user-details.php?token={$token}'>{$row['id']}</a>
  3. On the target page, retrieve the token from the URL, look up the corresponding ID in Redis, then delete the token to prevent reuse.

Pros: Raw ID is never exposed. Cons: Requires setting up Redis (or similar) and adds complexity.


Final Recommendation

Stick with URL query parameters unless you have a specific reason to hide the ID. It's simple, reliable, and fits all your constraints perfectly.

内容的提问来源于stack exchange,提问作者joebegborg07

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:55:54