根据 URL 参数重定向,如果 URL 参数在表行中可用 - PHP MySQL

Posted

技术标签:

【中文标题】根据 URL 参数重定向,如果 URL 参数在表行中可用 - PHP MySQL【英文标题】:Redirect based on URL parameter and if URL parameter is available in table row - PHP MySQL 【发布时间】:2016-07-05 13:07:36 【问题描述】:

我有一张表,其中一个属性是版本。

表名是versions。

如果 URL 参数(也称为版本)为 NULL 或不存在,并且版本值不在我的表中,我想将用户重定向到默认页面。

到目前为止,我有这个。它不起作用。

$stonevar = isset($_GET['version']) ? $_GET['version'] : NULL;

if (empty($stonevar)) 
header("Location: index.php?version=default");
 

$id = $_GET['version'];
$result = $db->query("SELECT * FROM `versions` WHERE version='$id'");

 while ($row = $result->fetch_assoc()) 
  $varex = $row['version'];
 

if ($varex == NULL) 
header("Location: index.php?default");

【问题讨论】:

【参考方案1】:

使用$result->num_rows统计结果,看看版本是否存在。

$stonevar = isset($_GET['version']) ? $_GET['version'] : NULL;

if (empty($stonevar)) 
header("Location: index.php?version=default");
 

$id = $_GET['version'];
$result = $db->query("SELECT * FROM `versions` WHERE version='$id'");

$total_num_rows = $result->num_rows;

if ($total_num_rows>0) 
    while ($row = $result->fetch_assoc()) 
        $varex = $row['version'];
    

else
    header("Location: index.php?default");

【讨论】:

【参考方案2】:

你必须添加 exit();在标头函数之后。

试试类似的东西:

  <?php
    $stonevar = isset($_GET['version']) ? $_GET['version'] : NULL;

    if (empty($stonevar)) 
    header("Location: index.php?version=default");
    exit();
     

    $result = $db->query("SELECT * FROM `versions` WHERE version='$stonevar'");

     while ($row = $result->fetch_assoc()) 

    header("Location: index.php?".$row['version']);
    exit();
/*
* or something you want to do if version exist
*/
     

    header("Location: index.php?default");
    exit();
    ?>

【讨论】:

以上是关于根据 URL 参数重定向,如果 URL 参数在表行中可用 - PHP MySQL的主要内容,如果未能解决你的问题,请参考以下文章

基于 URL/查询参数的重定向

htaccess url重定向参数不起作用

根据发送的参数进行动态重定向php

反向解析与重定向 | Django开发

使用 URL 参数的 PHP 重定向

Flask url 重定向给出了意外的关键字参数异常