将信息带到第二个 php 文件中,但 SESSION 不是答案


Bringing information to a 2nd php file, but SESSION isn't the answer

我有file1.php和file1.php。我想要一个从 file1.php 到 file2.php 的 ID(存储在数据库中),但我通过<a href=链接到第 2 页 必须转到 file2 的 ID 号.php取决于我单击的链接。所以SESSIONS可能不会这样做。我用SESSIONS试过了,但当我测试它时它只记得 1 个 ID 号。

这是 file1 中的行.php它的全部内容:

while ($thread = mysqli_fetch_assoc($sql_result)) {
<a href="thread.php?thread_id={$thread['thread_id']}"> {$thread['title']} </a>
}

这个while循环确保我的数据库中的每个不同标题都获得一个链接(指向file2.php),其中包含属于thread_id的必要信息。 (thread_id是我的数据库中唯一必须与其他标题不同的内容)

所以现在要在 file2 中显示它.php我得到了这个:

$sql_result = $mysqli2->query("SELECT * FROM questions WHERE thread_id = '".The ID Number of the link of file1.php."'");
    while ($thread = mysqli_fetch_assoc($sql_result)) {
echo <<<EOT
        <table>
            <tr>
                <tr><td> {$thread['title']}</td></tr>
                <tr><td> {$thread['description']}</td></tr>
                <tr><td> {$thread['username']}</td></tr>
                <tr><td> {$thread['date_made']}</td></tr>
            </tr>       
</table>
EOT;

以显示属于thread_id的信息。我该怎么做?

通过单击该链接,您不会在会话中存储任何内容。

您需要使用$_GET

例:

$thread_id = $_GET['thread_id'];
if(!is_numeric($thread_id)){
   // Exit the script as the Thread ID isn't numeric or do something else
   echo 'THREAD ID NOT NUMERIC';
   exit;
}
$sql_result = $mysqli2->query("SELECT * FROM questions WHERE thread_id = '".$thread_id."'");
    while ($thread = mysqli_fetch_assoc($sql_result)) {
echo <<<EOT
        <table>
            <tr>
                <tr><td> {$thread['title']}</td></tr>
                <tr><td> {$thread['description']}</td></tr>
                <tr><td> {$thread['username']}</td></tr>
                <tr><td> {$thread['date_made']}</td></tr>
            </tr>       
</table>
EOT;

您必须过滤来自 $_GET 变量的输入,因为这是一个简单的 SQL 注入向量。

$link=$mysqli2->real_escape_string($_GET['thread_id']);
$sql_result = $mysqli2->query("SELECT * FROM questions WHERE thread_id = '$link'");

使用$_SESSION来解决这样的问题并不是最好的主意,但你没有对代码中的会话做任何事情,所以我假设你已经发现了这一点。

基本上你走在正确的道路上,你创建链接列表的方式很好!

现在,在新页面上,您希望再次从查询字符串中检索该 ID,这就是 $_GET 全局数组发挥作用的地方。

使用查询字符串中的参数从数据库检索数据的正确方法是:

if (!isset($_GET['thread_id'])) {
    // route back to the list or throw an error or something
}
// cast the param to int to sanitize it, 
// no real_escape_string needed in the int case
$thread_id = (int) $_GET['thread_id'];
// get the info from the database BUT use parameterized queries!
$stmt = $mysqli2->prepare("SELECT * FROM questions WHERE thread_id = ?");
$stmt->bind_param($thread_id);
$stmt->execute();