简体   繁体   English

在PHP中依次查询多个MSSQL表中的一个值

[英]Query for one value in multiple MSSQL tables sequentially in PHP

I have 2 tables i need to query for a single result, but if it's found in $table0, I need to stop searching and use the values in that row.我有 2 个表需要查询单个结果,但如果在 $table0 中找到它,我需要停止搜索并使用该行中的值。 Something like this:像这样的东西:

$p1_sql = "SELECT TOP 1 * FROM '$table0' WHERE phone1 = '$cidnumber'";
$p2_sql = "SELECT TOP 1 * FROM '$table0' WHERE phone2 = '$cidnumber'";
$c1_sql = "SELECT TOP 1 * FROM '$table1' WHERE contactphone = '$cidnumber'";
$c2_sql = "SELECT TOP 1 * FROM '$table1' WHERE contactphone2 = '$cidnumber'";
$c3_sql = "SELECT TOP 1 * FROM '$table1' WHERE contactphone3 = '$cidnumber'";
$c4_sql = "SELECT TOP 1 * FROM '$table1' WHERE contactphone4 = '$cidnumber'";

$p1_res = mssql_query($p1_sql);
$p1_row = mssql_num_rows($p1_res);

$p2_res = mssql_query($p2_sql);
$p2_row = mssql_num_rows($p2_row);

$c1_res = mssql_query($c1_sql);
$c1_row = mssql_num_rows($c1_res);

$c2_res = mssql_query($c2_sql);
$c2_row = mssql_num_rows($c2_res);

$c3_res = mssql_query($c3_sql);
$c3_row = mssql_num_rows($c3_res);

$c4_res = mssql_query($c4_sql);
$c4_row = mssql_num_rows($c4_res);

if ($p1_row = 1){
    $p1_res = $newres;
    goto okres;
} elseif ($p2_row = 1) {
    $p2_res = $newres;
    goto okres;
} elseif ($c1_row = 1) {
    $c1_res = $newres;
    goto okres;
} elseif ($c2_row = 1) {
    $c2_res = $newres;
    goto okres;
} elseif ($c3_row = 1) {
    $c3_res = $newres;
    goto okres;
} elseif ($c4_row = 1) {
    $c4_res = $newres;
    goto okres;
} else {
    $newres = "na";
    goto nares;
}

okres:
$cid_sel = mssql_query("SELECT TOP 1 * FROM '$table0' WHERE phone1 = '$cidnumber'");

This, however, is ugly and doesn't work.然而,这很丑陋并且不起作用。 I was trying to use 'for each...' or 'while (something)', but couldn't wrap my head around how it would work.我试图使用“for each...”或“while (something)”,但无法理解它是如何工作的。 I don't even know if it would.我也不知道会不会。 What's the best way to go about this? go 关于这个的最佳方法是什么? It's my first forray into something like this and any help is appreciated.这是我第一次尝试这样的事情,任何帮助表示赞赏。

It's unnecessary to do so many separate queries.没有必要做这么多单独的查询。 Are you familiar with basic SQL, as far as JOINs and UNIONs?您是否熟悉基本的 SQL,就 JOIN 和 UNION 而言? If not you should read on them-- what you want here seems achievable with a single query.如果不是,你应该阅读它们——你想要的似乎可以通过一个查询来实现。

I would add the different queries in to an array and loop (using foreach) that array to subsequent query the database.我会将不同的查询添加到一个数组中并循环(使用 foreach)该数组以随后查询数据库。 As soon as you find what you're looking for you break out of the loop using the break;一旦你找到你要找的东西,你就使用 break 跳出循环; command.命令。

Using joins in pure sql could also be a solution, but I'm not entirely sure what you wish to achieve here.在纯 sql 中使用连接也可能是一种解决方案,但我不完全确定您希望在这里实现什么。

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM