PHP / MySQL搜索结果。如果只有一个结果,则自动重定向

时间:2015-05-07 12:59:32

标签: php mysql

我在PHP中有多个带有While循环的SQL查询用于搜索表单。

总共有3个代码块,每个代码块都是从不同的表中选择的,在使用

的while循环之前
if(mysql_num_rows($rs) > 0) {
    ...show results here
}

我想拥有它,如果3块代码只返回一个结果,它会自动重定向到另一个页面。

例如,我正在搜索客户,联系人和发票。所以它们是我拥有的3个不同的代码/查询块。

如果我搜索公司A并且客户查询中返回了1条记录,并且在“联系人”和“发票”中返回了0条记录,则应重定向到客户页面。但是,如果返回了2条记录,则应该只显示搜索结果。

和客户,联系人和发票相同

3 个答案:

答案 0 :(得分:1)

要重定向到新页面,请使用header()

header("Location: /url/to/company/page?id=$companyId");

您的条件需要处理至少三种情况:无结果,单个结果和多个结果:

switch (mysql_num_rows($rs)) {
    case 0:
        $this->noResultsFound();
        break;
    case 1:
        header("Location: /url/to/company/page?id=" . $rs[0]['companyId']);
        break;
    default:
        $this->showResults($rs);
        break;
 }

如评论中所述,mysql_*函数已弃用;它们已被更好,更安全的替代品所取代。考虑调查PDO的好处。

在生产代码中使用die()语句通常是不好的做法。但是,少数例外情况之一与header()的使用相关。这可能不是很明显,但是当您使用header()重定向时,脚本的其余部分将继续运行,然后将带有重定向指令的HTTP标头发送到浏览器。对于结构不良的代码,这可能会导致意外的结果。

要避免此问题,请在die()行后立即插入header()语句。

答案 1 :(得分:0)

以下是否足够?

if (mysql_num_rows($result) == 1) {
    header("Location: other_script.php");
} elseif (mysql_num_rows($result) > 1) {
    // ... show results ...
} else {
    // ... no results ...
}

如果我理解你的问题是错误的并且你有多个查询但想知道总结果,那就简单如下:

$one = mysql_num_rows($result_one);
$two = mysql_num_rows($result_two);
$three = mysql_num_rows($result_three);
$total = $one + $two + $three;
if ($total == 1) {
    header("Location: other_page.php");
}

答案 2 :(得分:0)

这是极其简化的代码,可以进行高度优化,但我认为这正是您所需要的。

//After queries you've got 3 arrays:
$customers = [...];
$contacts = [...];
$invoices = [...];

//Determine if there's only 1 result of 1 category returned from the queries:
if(sizeof($customers)==1 && sizeof($contacts)==0 && sizeof($invoices)==0){
// Redirect to customers...
} elseif(sizeof($customers)==0 && sizeof($contacts)==1 && sizeof($invoices)==0) {
// Redirect to contacts...
} elseif(sizeof($customers)==0 && sizeof($contacts)==0 && sizeof($invoices)==1){
// Redirect to invoices...
} else {
// Redirect to results page...
}