PHP PDO 准备的查询拒绝正确执行 - 转义问题?
我在使用 PDO 在 PHP 中准备的查询时遇到问题。 代码:
$link = new PDO("mysql:dbname=$dbname;host=127.0.0.1",$username,$password);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $link->prepare("SELECT locality_name FROM :passedday GROUP BY locality_name ORDER BY locality_name DESC");
$query->bindParam(":passedday",$day); //Where day is, well, a day passed to the script elsewhere
$query->execute();
$result = $query->fetchAll();
$link = null;
//Do things with the $result.
我收到的错误消息是:
SQLSTATE[42000]: 语法错误或访问冲突: 1064 您的 SQL 语法有错误; 检查与您的 MySQL 服务器版本相对应的手册,了解在第 1 行的 ''05_26_09' GROUP BY locality_name ORDER BY locality_name DESC' 附近使用的正确语法
当我直接在服务器上执行查询时,它返回适当的结果集,没有任何问题。 有什么想法我做错了吗?
TIA。
编辑:
$day
作为 GET 参数传递。 因此,http://127.0.0.1/day.php?day=05_26_09
会导致 $day = $_GET['day'];
。
I'm having a problem with a query prepared in PHP with PDO. The code:
$link = new PDO("mysql:dbname=$dbname;host=127.0.0.1",$username,$password);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $link->prepare("SELECT locality_name FROM :passedday GROUP BY locality_name ORDER BY locality_name DESC");
$query->bindParam(":passedday",$day); //Where day is, well, a day passed to the script elsewhere
$query->execute();
$result = $query->fetchAll();
$link = null;
//Do things with the $result.
The error message I am getting is:
SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''05_26_09' GROUP BY locality_name ORDER BY locality_name DESC' at line 1
When I execute the query on the server directly, it returns the appropriate result set without any problem. Any ideas what I'm doing wrong?
TIA.
Edit:
$day
is passed as a GET argument. So, http://127.0.0.1/day.php?day=05_26_09
leads to $day = $_GET['day'];
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
05_26_09
应该押注桌子的名称,那么我猜你遇到了转义问题。 您的本地操作系统与实时服务器不同吗?我认为您不能将
bindValue()
/bindParam()
用于值以外的其他内容(例如表名、字段名)。 所以我有点惊讶它可以在你的本地系统上运行。If
05_26_09
is supposed to bet the table's name, then I guess you've an escaping problem. Is your local operating system different from the live server?I don't think you can use
bindValue()
/bindParam()
for something else than values (eg. table name, field name). So I'm a bit suprised, that it works on your local system.PDO 使用 mysql 的 C-API 来准备语句。
http://dev.mysql.com/doc/ refman/5.0/en/mysql-stmt-prepare.html 说:
As a rule of thumb I use: "if you can't wrap it in single-quotes in an ad-hoc query string you can't parametrize it in a prepared statement"
PDO uses mysql's C-API for prepared statements.
http://dev.mysql.com/doc/refman/5.0/en/mysql-stmt-prepare.html says:
As a rule of thumb I use: "if you can't wrap it in single-quotes in an ad-hoc query string you can't parametrize it in a prepared statement"