SQL有什么问题?
问题描述:
我正在尝试使用PDO,所以我将其结合在一起:
I'm trying to use PDO, so i got this together:
所以$_GET['word'] = "Jimi Hendrix"
和$_GET['cat'] = "music"
.
$now = htmlentities(rawurldecode($_GET['word']));
$cat = htmlentities($_GET['cat']);
$dsn = 'mysql:dbname=DATABASE;host=localhost';
$user = "USER";
$password = "PASS";
# connect to the database
try {
$DBH = new PDO($dsn, $user, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
# the data to select
$data = array($cat, $now);
$STH = $DBH->prepare("SELECT id, name FROM ? WHERE name LIKE ?");
$STH->execute($data);
$result = $STH->fetchAll();
}
catch(PDOException $e) {
echo "Uh-Oh, something wen't wrong. Please try again later.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
echo "<pre>";
print_r($result);
echo "</pre>";
但是上面的代码正在返回:
But the code above is returning:
SQLSTATE[42000]: Syntax error or access violation: 1064 You Have a Syntax error in your SQL near ''music' WHERE name LIKE 'Jimi Hendrix'' on line 1
答
将类别转换为字符串,并在准备查询时将其转换为:
The category is converted into a string and when the query is prepared it is converted into:
SELECT id, name FROM 'cat' WHERE name 'music'
该表不应为字符串,您可以执行以下操作:
The table shouldn't be a string, what you can do is:
# the data to select
$data = array($now);
$STH = $DBH->prepare("SELECT id, name FROM $cat WHERE name LIKE ?");
$STH->execute($data);