1

我正在尝试使用 SQL 数据库在 PHP 中编写查找工具。

$sql="SELECT  
         ID, 
         switch, 
         vlan, 
         circuit_id 
      FROM vlan 
      WHERE switch 
      LIKE LOWER('%" . $name .  "%') OR vlan='" . $name ."' 
      ORDER BY vlan";

然后再往下,我将结果放入变量中:

while($row=mysql_fetch_array($result)){
      $switch  =$row['switch'];
      $vlan=$row['vlan'];
      $circuitID=$row['circuit_id'];
      $ID=$row['ID'];

我想要做的是获取交换机回复并使用它在名为 router 的不同表上执行另一个查询并返回该信息。

我已经搜索了几天,我所有的搜索都在这里结束了,但似乎不太合适。我感谢您提供的任何帮助。

更新 有了一些很好的答案,我终于得到了这个工作。这是我的做法。谢谢您的帮助。

while($row=mysql_fetch_assoc($result)){
      $switch  =$row['switch'];
      $vlan=$row['vlan'];
      $circuitID=$row['circuit_id'];
      $ID=$row['ID'];
      $sql2 = "SELECT IPAddress FROM router 
                WHERE switch LIKE '%".$switch."%'
                LIMIT 1";         
      $result2 = mysql_query($sql2);
      $row2=mysql_fetch_array($result2);
      $IPAddress = $row2['IPAddress'];

对于更有经验的人来说可能真的很难看,但它确实有效。再次感谢。

4

2 回答 2

0

How many results do you expect? If there's more than one result, you might need to point which row exactly you want to take. Since it's fetch_array, your $row['switch'] or $switch value is still an array. var_dump it for keys and use the key, i.e.

SELECT `col` FROM `router` WHERE `switch` = '$switch[1]'
于 2013-03-30T20:51:00.443 回答
0

It would be highly inefficient to run a secondary lookup query in a loop.

What you want is a simple JOIN between your two tables based on the switch field. What this will do is bring the linked rows in your router table alongside the rows in your vlan table where values in the switch column match up:

$sql = '
    SELECT   a.id, a.switch, a.vlan, a.circuit_id, b.ipaddress
    FROM     vlan a
    JOIN     router b ON a.switch = b.switch
    WHERE    a.switch LIKE "%' . strtolower($name) . '%" OR vlan = "' . $name . '"
    ORDER BY a.vlan';

Then in your same fetch loop, you'll be able to access the linked values from your router table without having to run extra database calls:

while($row=mysql_fetch_array($result)){
     $switch  =$row['switch'];
     $vlan=$row['vlan'];
     $circuitID=$row['circuit_id'];
     $ID=$row['ID'];
     $ipaddress = $row['ipaddress'];
}
于 2013-03-30T21:45:14.363 回答