在SQL查询中转义特殊字符

时间:2012-08-28 13:46:40

标签: php sql special-characters

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

  

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

     

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

     

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

     

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

     

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

我知道这是一个转义特殊字符的问题,但有没有办法在查询中执行此操作,还是必须在表中执行此操作?

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

Women's Softball coach

以下是查询的执行方式:

$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"; 
}

1 个答案:

答案 0 :(得分: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 documentation on prepared statement

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

$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(); 
        ...
}