SQL有什么问题? [英] What is wrong with the SQL?

查看:59
本文介绍了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);

这篇关于SQL有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆