使用唯一列名从PHP运行SQL查询?

时间:2015-09-09 19:11:07

标签: php sql sql-server sql-server-2012

我已经运行了很多次SQL查询。通常这就是我所做的:

$conn = sqlsrv_connect( $serverName, $connectionInfo);    
$sql = "SELECT AREA,UNIT,COMPLEX,PROPERTY FROM TrimTable";
    $query = sqlsrv_query($con

if ($query === false){  
     echo "Could not link to SQL Server";
}
while ($row = sqlsrv_fetch_array($query))
{   
      $AREA[] = "$row[AREA]";
      $UNIT[] = "$row[UNIT]";
      $COMPLEX[] = "$row[COMPLEX]";
      $PROPERTY[] = "$row[PROPERTY]";            
}  

在此之后我使用我的阵列并按照我想要的方式操纵它们。这个特殊的代码在顶部工作。但我在表中列出了几个名为unique的列。表中的一列是LOOP TYPE。还有ID#列。我在网上看了但是找不到任何东西。我如何对这些进行查询?

更新 这是我正在尝试的代码:

$conn = sqlsrv_connect( $serverName, $connectionInfo);
$sql = "SELECT AREA,UNIT,COMPLEX,`LOOP TYPE` as LOOP, PROPERTY FROM TrimTable";
$query = sqlsrv_query($conn,$sql);
if ($query === false){  
       echo "Could not link to SQL Server";
}
while ($row = sqlsrv_fetch_array($query))
{   
    print_r($row);
}  

1 个答案:

答案 0 :(得分:0)

在查询中使用括号和别名:

$conn = sqlsrv_connect( $serverName, $connectionInfo);    
$sql = "SELECT AREA,UNIT,COMPLEX,PROPERTY, [LOOP TYPE] as LOOP, [ID#] as ID FROM TrimTable";
$query = sqlsrv_query($conn,$sql);

if ($query === false){  
    echo "Could not link to SQL Server";
}
while ($row = sqlsrv_fetch_array($query))
{   
    $AREA[] = "$row[AREA]";
    $UNIT[] = "$row[UNIT]";
    $COMPLEX[] = "$row[COMPLEX]";
    $PROPERTY[] = "$row[PROPERTY]";      
    $LOOPTYPE[] = "$row[LOOP]";              
    $ID[] = "$row[ID]";    
}