我有一个相当简单的查询,我想用我的PDO连接到远程MSSQL服务器运行。
SELECT BookingID, DriverID
FROM dbo.VehicleJobHistory
WHERE TimeJobRequired > "02/03/2013" AND VehicleID = $vid
当我在没有任何变量的情况下编写查询时,它完美地运行,但是当我尝试向查询添加变量时,我什么都没有返回。我认为它的类型不匹配,但我无法确定。
如果我将$ vid更改为“451”,我会得到我想要的结果。
$vid = '451';
$myServer = "X";
$myUser = "X";
$myPass = "X";
$myDB = "X";
try {
# MS SQL Server and Sybase with PDO_DBLIB
$DBH = new PDO("dblib:host=$myServer;dbname=$myDB", $myUser, $myPass);
# creating the statement
$STH = $DBH->query('SELECT BookingID, DriverID FROM dbo.VehicleJobHistory WHERE TimeJobRequired > "02/03/2013" AND VehicleID = $vid');
# setting the fetch mode
$STH->setFetchMode(PDO::FETCH_OBJ);
# showing the results
while($row = $STH->fetch()) {
echo $row->BookingID . "/";
echo $row->DriverID ;
echo "<br>";
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
# close the connection
$DBH = null;
echo "connection closed";
非常感谢任何帮助。
答案 0 :(得分:2)
这是因为您的查询是在单引号字符串中定义的。变量$vid
不会在单个带引号的字符串中进行插值,并作为文字$vid
传递,从而导致查询语法错误,因为它没有引用。使用外部的双引号反转引号。
$STH = $DBH->query("SELECT BookingID, DriverID FROM dbo.VehicleJobHistory WHERE TimeJobRequired > '02/03/2013' AND VehicleID = $vid");
实际上,这应该通过准备好的陈述和bindParam()
VehicleID
来完成。
$stmt = $DBH->prepare("SELECT BookingID, DriverID FROM dbo.VehicleJobHistory WHERE TimeJobRequired > '02/03/2013' AND VehicleID = :vid");
if ($stmt) {
$stmt->bindParam(':vid', $vid);
$stmt->execute();
}
开始阅读PDO prepared statements。如果您使用的是PDO,则应确保获得安全保障。