Unable to quote table name in PDO with MSSQL

落爺英雄遲暮 提交于 2019-12-12 12:26:39

问题


I have to work with somebody's database for a game which sadly has a table named "User" or [dbo][User] and this can not be renamed. Now, I need to access this using PDO in PHP and when I use this query:

$query = "SELECT UserId AS INTUSERID FROM dbo.User WHERE YahooId = 'abcdef'";

it fails, as in nothing is fetched since "User" is a reserved keyword there. From the MS SQL Server I can do this as:

SELECT UserId AS INTUSERID FROM [GameName].[dbo].[User] WHERE YahooId = 'abcdef'

and it works. How should I prepare my query in PHP to make this execute? I have tried to put single quotes around table name but that has no effect. What is the correct way to use

[GameName].[dbo].[User] 

from PHP PDO as the table name ?

Update: This is how I am connecting:

try{
    $conn = new PDO("xxx.rds.amazonaws.com,1150;Database=xyz","admin","password");
    } catch(PDOException $e){
        echo "Connection failed: " . $e->getMessage();
    }

回答1:


Further to the discussion in the comments I am providing this so that the question has an answer. I thought square brackets would work fine within the php string used to define the query so I tested it out on my own code that connects to MS-SQL using PDO.

So the following should work...

$query = "SELECT UserId AS INTUSERID FROM dbo.[User] WHERE YahooId = 'abcdef'";

Side note - If your YahooId ever comes from a source that can be manipulated by a user (such as $_GET) you should research Prepared Statements with PDO...

$query = "SELECT UserId AS INTUSERID FROM dbo.[User] WHERE YahooId = ?;";

$statement= $db->prepare($query);

$statement->execute(array($userinput));


来源:https://stackoverflow.com/questions/21348209/unable-to-quote-table-name-in-pdo-with-mssql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!