1

我有一个 SQL Server 表,其中包含部门名称(即Admissions & RegistrationWomen's Softball coach),当您单击我们页面上的链接时,它会拉出该部门下的所有员工,但是当您拉出时,Women's Softball coach我收到如下错误:

PHP 警告:mssql_query() [function.mssql-query]:> 消息:第 1 行:“s”附近的语法不正确。(严重性 15)在 >C:\Inetpub\wwwroot\DACC\directory\dept.php 第 179 行

PHP 警告:mssql_query() [function.mssql-query]: >message: 字符串 ') ORDER BY Lastname' 前的未闭合引号。>>>(严重性 15)在 C:\Inetpub\wwwroot\DACC\directory\dept.php 第 179 行

PHP 警告:mssql_query() [function.mssql-query]: >第 179 行 C:\Inetpub\wwwroot\DACC\directory\dept.php 中的查询失败

PHP 警告:mssql_query() [function.mssql-query]:消息:第 5 行:“s”附近的语法不正确。(严重性 15)在 >C:\Inetpub\wwwroot\DACC\directory\dept.php 第 195 行

PHP 警告:mssql_query() [function.mssql-query]: >message: 字符串“ORDER BY directory.LastName”前的未闭合引号。(严重性 15)在 C:\Inetpub\wwwroot\DACC\directory\dept.php >在第 195 行

我知道这是转义特殊字符的问题,但是有没有办法在查询中做到这一点,或者我必须在表中做到这一点?

上面引用的代码在这里--->

$department = $_GET['dept'];

// This will evaluate to TRUE so the text will be printed.
if (isset($department)) {

 // Send a select query to MSSQL

$query = mssql_query("SELECT * FROM directory WHERE department IN (SELECT id FROM     departments WHERE name='$department') ORDER BY Lastname");

以下是查询的执行方式:

   function listDepts() { 

    $query = "SELECT DISTINCT name FROM departments ORDER BY name"; 
    $result = mssql_query($query); 
    echo "<h3>Please select a department:</h3>\n"; 
    echo "<ul>\n"; 

    for ($i=0; $i<mssql_num_rows($result); $i++) { 
        $info = mssql_fetch_assoc($result); 
        echo "<li><a href=\"dept.php?dept=$info[name]\">$info[name]</a></li>\n"; 
    } 

    echo "</ul>\n\n"; 
}

这是生成部门列表的代码。

 function listDepts() {

$query = "SELECT DISTINCT  name FROM     departments ORDER BY     name";
$result = mssql_query($query);

echo "<h3>Please select a department:</h3>\n";
echo "<ul>\n";

for ($i=0; $i<mssql_num_rows($result); $i++) {
    $info = mssql_fetch_assoc($result);
    echo "<li><a href=\"dept.php?dept=$info[name]\">$info[name]</a></li>\n";
}

echo "</ul>\n\n";

 }
4

1 回答 1

1

我强烈建议您使用准备好的语句,然后使用变量执行它:

$stmt = $dbh->prepare("SELECT * FROM directory WHERE department IN (SELECT id FROM departments WHERE name=?) ORDER BY Lastname");
if ($stmt->execute(array("Women's Softball coach"))) {
    while ($row = $stmt->fetch()) {
        print_r($row);
    }
}

有关详细信息,请参阅有关准备好的语句的 PHP 文档。

在你的具体情况下,你会有这样的事情:

$stmt = $dbh->prepare("SELECT * FROM directory WHERE department IN (SELECT id FROM departments WHERE name=?) ORDER BY Lastname");
for ($i=0; $i<mssql_num_rows($result); $i++) {
    if ($stmt->execute(array($result))) {

        $info = $stmt->fetch(); 
        ...
} 
于 2012-08-28T14:00:29.053 回答