doumeng3080 2012-06-27 18:11
浏览 52
已采纳

PDO - 引号正在生成MySQL语法错误

I'm trying to bind parameters in what I think is the correct way, but I get a 1064 error from MySQL, suggesting that there are too many quotes involved. The written code looks like this:

$db_host = 'localhost';
$db_username = 'root';
$db_password = 'Password123';
$db_database = 'db_test';

$dbh = new PDO("mysql:host=$db_host", $db_username, $db_password);
$stmt = $dbh->prepare("DROP DATABASE :db_database;");
$stmt->bindParam(':db_database', $db_database, PDO::PARAM_STR, 7);
$stmt->execute() or exit(print_r($stmt->errorInfo(), true));

and displays the error message:

Array ( [0] => 42000 [1] => 1064 [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''db_test'' at line 1 )

It worked fine when I inserted the variable $db_database the wrong way, i.e. directly into the sql syntax. Also, I have checked that magic_quotes are turned off, if that has any impact on it. Right now I'm stuck, because it feels like I have done things correctly (but obviously I haven't). Can anyone see the error?

  • 写回答

2条回答 默认 最新

  • dousui7410 2012-06-27 18:22
    关注
    1. You are using emulation it seems, because the database wouldn't even let you PREPARE this (set $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);)
    2. You can NOT name identifiers (column/table/databasenames), functions, etc. in parameters, that is not how prepared statements work, you can only send 'true' strings / floats / ints. In short, if you need an identifier or function name somewhere, it should be in the query before your ->prepare() it.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 链接问题 C++LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接