在SQLSRV获取数组命令中使用WHERE参数

时间:2014-09-08 16:44:41

标签: php sql-server sqlsrv

我这里有一段代码

$sql = "SELECT ID, Registration, InGarage, BeingServiced, ReadyForCollection WHERE Registration = $numberPlate FROM SomeTable";

我得到的回应是

Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 156 [code] => 156 [2] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near the keyword 'FROM'. [message] => [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near the keyword 'FROM'. ) ) 

但如果我删除了

WHERE Registration = $numberPlate

部分,它运作正常吗?我必须使用什么来代替WHERE参数?

更新

新代码

$sql = "SELECT ID, Registration, InGarage, BeingServiced, ReadyForCollection FROM SomeTable WHERE Registration = $numberPlate ";

更新

回声代码

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
  while($row['InGarage'] = $comp and $row['BeingServiced'] = $unco and $row['ReadyForCollection'] = $unco) {
    echo "Vehicle is in Garage";
}
  while($row['InGarage'] = $comp and $row['BeingServiced'] = $comp and $row['ReadyForCollection'] = $unco) {
    echo "Vehicle is being serviced";
}
  while($row['InGarage'] = $comp and $row['BeingServiced'] = $comp and $row['ReadyForCollection'] = $comp) {
    echo "Vehicle is ready for collection";
}

}

2 个答案:

答案 0 :(得分:1)

你的FROM和你的WHERE条款有错误的方法:

$sql = "SELECT ID, Registration, InGarage, BeingServiced, ReadyForCollection FROM SomeTable WHERE Registration = $numberPlate ";

您可能也应该使用parameterised queries。至少,如果Registration是VARCHAR类型,您可能需要$ numberPlate周围的引号:

$sql = "SELECT ID, Registration, InGarage, BeingServiced, ReadyForCollection FROM SomeTable WHERE Registration = '$numberPlate' ";

如果$ numberPlate来自用户输入,你应该肯定使用参数化查询,否则你将容易受到SQL注入攻击:

$sql = "SELECT ID, Registration, InGarage, BeingServiced, ReadyForCollection FROM SomeTable WHERE Registration = ?";
$stmt = sqlsrv_query( $conn, $sql, array($numberPlate));

答案 1 :(得分:0)

您的查询应该是

$sql = "SELECT ID, Registration, InGarage, BeingServiced, ReadyForCollection 
        FROM SomeTable WHERE Registration = '$numberPlate' ";

首先是from语句,然后是where语句。