Querying table with an ampersand in the name
I'm in the process of cleaning up a MySQL database and have to make some similar changes across multiple tables. As such, I gather my list of tables
$query = "
SELECT
TABLE_NAME
FROM
information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'myDB' AND
COLUMN_NAME = 'activeColumn'";
then iterate through each making the changes I need. The problem is that some of these tables have an ampersand in the title. I guess PHP and/or MySQL has a problem with this, as it throws this my direction
/* $query = "SELECT * FROM Cats&Dogs"; */
You have an error in your SQL syntax;
check the manual that corresponds t开发者_如何学编程o your MySQL server version for the
right syntax to use near '&Dogs' at line 1
I've found ways to fix this issue when you need to insert an ampersand in to the DB and even when you have one in the WHERE clause(truthfully, this isn't even a full solution but it's the best I found). If I enter the exact query in to MySQL without using PHP then it works.
What could be causing this issue?
Backticks. SELECT * FROM `Cats&Dogs`
.
Reference: http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
Try escaping table name using reverse single quote:
SELECT * FROM `Cats&Dogs`;
use addslashes()
when you post input to database and use stripslashes()
when get from datase, this will allow special characters to store and retrieve in database
精彩评论