问题
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