2016-07-15 10:59

在PHP中的MS SQL查询中转义$字符[重复]


This question already has an answer here:

I have a situation under which I have to use $ (dollar sign) inside a MS SQL query since the table is named this way (e.g. [My company name$Fixed Asset].[Description]), but PHP recognizes part "$Fixed" as a variable and then later on when I try to execute the code in the browser it throws an error e.g. "Notice: Undefined variable: Fixed".

How do I escape this character?

Here is the part of the code I am trying to use:

    if (isset($_POST['submit'])) {
        if ($_POST['password'] === 'mypass') {

            $result = mssql_query("SET ANSI_NULLS ON;");
            $result1 = mssql_query("SET ANSI_WARNINGS ON;"); 
            $query = mssql_query("

TRUNCATE TABLE [fixed_assets].[dbo].[fa_masterdata];

INSERT INTO [fixed_assets].[dbo].[fa_masterdata]

[My company name$Fixed Asset].[No]
,[My company name$Fixed Asset].[Description]
,[Search Description]
,[Description 2]
,[Location Code]
,[Vendor No_]
,[My company name$FA Depreciation Book].[Disposal Date]
,[My company name$FA Location].[Name]
,[My company name$Comment Line].Code
,[My company name$Comment Line].Comment
FROM [SQL SERVER NAME\INSTANCE].[MY COMPANY].[dbo].[My company name$Fixed Asset]

full outer join [SQL SERVER NAME\INSTANCE].[MY COMPANY].[dbo].[My company name$FA Location]
on [My company name$Fixed Asset].[FA Location Code] = [My company name$FA Location].[Code]

full outer join [SQL SERVER NAME\INSTANCE].[MY COMPANY].[dbo].[Record Link]
on [My company name$Fixed Asset].[No_] = convert(varchar(100),SUBSTRING([Record Link].[Record ID],8,8))

full outer join [SQL SERVER NAME\INSTANCE].[MY COMPANY].[dbo].[My company name$Comment Line]
on [My company name$Comment Line].[No_] = [My company name$Fixed Asset].[No_]

full outer join [SQL SERVER NAME\INSTANCE].[MY COMPANY].[dbo].[My company name$FA Depreciation Book]
on [My company name$FA Depreciation Book].[Fa No_] = [My company name$Fixed Asset].[No_]

where [My company name$Fixed Asset].[No_] != null");

    echo "<br/><br/><div class='alert alert-success col-sm-offset-5 col-sm-2'><span>Fixed assets data imported from NAV successfully!!</span></div>";
            } else {
                echo "<br/><br/><span>Import failed! (wrong password entered?)";


Please advise. Any suggestion is more than welcome.
Thank you all.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • drdr123456 drdr123456 5年前

    You can escape the $ and then it won't be read as a variable by PHP.

    echo "\$test";

    Demo: https://eval.in/605867 Vs. https://eval.in/605866 (which is empty because $test doesnt exist)


    or since your query doesn't use single quotes just use single quotes for the string encapsulation.

    echo '$test';
    点赞 评论 复制链接分享