我有多个SQL查询,wher wher wher php中的搜索表格中的循环。
总共有3个代码块,每个代码从另一个表中选择
if(mysql_num_rows($rs) > 0) {
...show results here
}
我想拥有它,因此,如果只有一个为3个代码块返回一个结果,它将自动重定向到其他页面。
例如,我正在寻找客户,联系人和发票。因此,它们是我拥有的3个不同的代码/查询块。
如果我搜索公司A,并且在客户查询中返回了1个记录,并且在联系人和发票中返回了0个记录,则应重定向到客户页面。但是,如果返回了2个记录,则应只显示搜索结果。
以及与客户,联系人和发票
重定向到新页面,使用 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标头发送到浏览器。对于结构差的代码,这可能会导致意外结果。
要避免该问题,请在header()
行之后立即插入die()
语句。
是否足够吗?
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");
}
这是极为简化的代码,可以高度优化,但我认为这是您想要的。
//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...
}